Display Name instead of ID in laravel 8

I have two tables: User and Organisation. User contains foreign key organisation_id referencing organisation. For viewing user, it shows error ‘Trying to get property ‘name’ of non object.

UserController

 public function view($id)
 {
  $record = User::find($id);
  return view('user.view',compact('record'));
 }

User.php

public function getOrg()
{
return $this->belongsTo(Organisation::class);
}

View.blade.php

<tr>
 <th>Organisation</th>
 <td>{{ $record->organisation_id->name }}</td>
</tr>

Try to refer another question and answer but still can’t solve it

>Solution :

In User.php your method name should be oranisation instead of getOrg. Laravel calls this method organisation() behind the scenes when accessing the $user->organisation property.

public function organisation()
{
    return $this->belongsTo(Organisation::class, 'organisation_id', 'id');
}

Then in view.blade.php a slight tweak:

<tr>
 <th>Organisation</th>
 <td>{{ $record->organisation->name }}</td>
</tr>

Leave a Reply