php - Attempt to read property "id" on null laravel 8 ← (PHP, Laravel)

Can someone help me? I have an error Attempt to read property "id" on null Laravel 8 while trying to show my table

Migration Tables

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username', 20)->unique();
            $table->string('password', 20);
            $table->enum('level',['admin', 'manager', 'pegawai']);
            $table->timestamps();
        });

Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->foreignId('id_user')
                ->constrained('users')
                ->onUpdate('cascade')
                ->onDelete('cascade');
            $table->string('nama_pgw', 50);
            $table->string('alamat');
            $table->string('no_telp', 13);
            $table->string('email', 30)->unique;
            $table->timestamps();

        });

Employee Model

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;
    protected $table = 'employees';
    protected $fillable = ['nama_pgw', 'username', 'alamat', 'no_telp', 'email'];

    public function user(){
        return $this->hasOne(User::class); 
    }
}

User Model

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;
    protected $table = 'users';
    protected $fillable = ['username', 'password', 'level'];

    public function employee(){
        return $this->belongsTo(Employee::class, 'id_user', 'id');
    }
}

User Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User;

class UserController extends Controller
{

    public function index()
    {

        $users = User::get();
        return view('user/index', compact('users'));
        
    }
}

Employee Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Employee;
use App\Models\User;

class PegawaiController extends Controller
{
    
    public function index()
    {

        $pegawai = Employee::get();
        return view('pegawai/index', compact('pegawai'));

    }
}

This is my view

<select name="id_user" id="username" class="uk-select">
    <option>- pilih username -</option>
        @foreach ($pegawai as $emp)
           option value="{{$emp->users->id}}">{{$emp->users->nama_pgw}}</option>
        @endforeach
</select>

Is it any problem on foreign key? I keep checking on typos possibility but everything seems right. thank you!

Answer



Solution:

Your relation in the employee Model is "user" while you are referring to it in blade view as "users".

Also, to run your code you can update your view:

<select name="id_user" id="username" class="uk-select">
    <option>- pilih username -</option>
        @foreach ($pegawai as $emp)
           <option value="{{$emp->user->id}}">{{$emp->user->nama_pgw}}</option>
        @endforeach
</select>

Edited:

I will also suggest optimizing your query by using eager loading. In your current code, it will execute n+1 queries where 1 query to retrieve employees and N queries to retrieve user for each employee

Update it with below code:

class PegawaiController extends Controller
{
    
    public function index()
    {

        $pegawai = Employee::with(['user'])->get();
        return view('pegawai/index', compact('pegawai'));

    }
}

Source