omrakhur omrakhur - 1 year ago 63
PHP Question

Laravel - trying to get information from row of same table using self ref FK

I have a table named

employees
in which exist the following columns:

-
id


-
firstname


-
lastname


-
manager_id


manager_id
is the ID of the row that belongs to an employee's manager. So if A is a manager of B, the
manager_id
in B's row would have the
id
of A.

In my
Employee
model, I have the following method:

public function manager(){
return Employee::where('id', $this->manager_id)->first();
}


In my view when I try to do the following:

@foreach($employees as $employee)
<tr>
<td style="width: 12%"><span class="fw-semi-bold">{{ $employee->firstname }}</span></td>
<td style="width: 12%"><span class="fw-semi-bold">{{ $employee->lastname }}</span></td>
<td style="width: 20%"><span class="fw-semi-bold">{{ $employee->manager()->firstname . ' ' . $employee->manager()->lastname }}</span></td></tr>
@endforeach


It gives the following error:

Trying to get property of non-object



I have tried to use
manager()->firstname
as well as
manager->firstname
in the view but each time the error is the same.

Answer Source

In you Employee model

public function manager()
{
  return $this->belongsTo('App\Manager','manager_id');
}

In view

@foreach($employees as $employee)
<tr>
 <td style="width: 12%"><span class="fw-semi-bold">{{ $employee->firstname }}</span></td>
 <td style="width: 12%"><span class="fw-semi-bold">{{ $employee->lastname }}</span></td>
 <td style="width: 20%"><span class="fw-semi-bold">@if($employee->manager) {{ $employee->firstname }} {{ $employee->lastname  }}@endif</span></td>
</tr>
@endforeach

Assuming your Manager.php model within the app directory. if not then please update the namespace in the first arguments of belongsTo() function.

Hope this will help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download