Home > Back-end >  ' Attemp to read property "basic_salary" on null ' error when I try to access fr
' Attemp to read property "basic_salary" on null ' error when I try to access fr

Time:11-30

In the 'Staff' Model I have

public function payroll(){
        return $this->hasOne(Payroll::class);
    }

And in the 'payroll' model I have

public function staff(){
        return $this->belongsTo(Staff::class);
    }

When I try to access payroll properties of specific 'staff' in a blade file,

<td>{{ $item->payroll->basic_salary }}</td>

if that 'staff' has a payroll record it works fine, but if the staff doesn't have a payroll record I get the error below:

Attempt to read property "basic_salary" on null

At first I did not have the relationship described in the 'Payroll' model, but then I did, and nothing changed

CodePudding user response:

If you are using php version 8 and above you could use nullsafe operator like this:

<td>{{ $item->payroll?->basic_salary ?? 'defaultValue' }}</td>

but if the php version is below 8 you could do something like this to check if payroll exists or not:

<td>{{ $item->payroll ? $item->payroll->basic_salary : 'defaultValue' }}</td>
  • Related