Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading