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
CodePudding user response:
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>
CodePudding user response:
First, your UserController does not have any bugs in it. However, consider using Implicit Route Model Binding to automatically fetch your User as an argument in your UserController method after you have gotten the rest of your code working.
Second, your User.php isn't defining the relationship according to Laravel's convention and I think that is a source of the problem. Prefer, instead, the following:
public function organisation()
{
return $this->belongsTo(Organisation::class);
}
The organisation()
method utilizes a "magic" method that allows you to fetch the full Eloquent model of the relationship using the following in view.blade.php
:
<tr>
<th>Organisation</th>
<td>{{ $record->organisation->name }}</td>
</tr>
Your code breaks for the following reasons:
- $record->organization_id is referring to the actual number in the db, not the related model. To get the related model in your example, you would need to do $record->getOrg(). However, for reasons stated above, you should rename that method to make better use of Laravel's conventions.
- Additionally, methods that begin with get...() are considered accessors to additional model attributes not found in the DB. So try to avoid using them for simple relationships.
Please let me know if you have any questions.
CodePudding user response:
you have define the relation in the query
public function view($id)
{
$record = User::with('getOrg')->find($id)->first();
return view('user.view',compact('record'));
}
In View
<tr>
<th>Organisation</th>
<td>{{ $record->getOrg->name }}</td>
</tr>
Try this way