'Laravel relationship hasMany not working
I want to print the name of the user by finding it with 'finished_by' column where id of user is stored. but i get this error:
Trying to get property 'name' of non-object
Inventory model has finished_by
which has user ID.
This is mine blade.php
@foreach($inventories as $inventory)
<tr>
<td>{{$inventory['id']}}</td>
<td>{{$inventory->user->name}}</td>
</tr>
@enforeach
and my index method
$company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();
return view('inventories', compact('inventories', 'companies'));
And mine relationships
Inventory.php
public function users(){
return $this->belongsTo(User::class, 'finished_by');
}
User.php
public function inventories(){
return $this->hasMany(Inventory::class, 'finished_by');
}
Solution 1:[1]
First change your relationship
Inventory.php
public function user(){
return $this->belongsTo("App\User", 'finished_by');
}
User.php
public function inventories(){
return $this->hasMany("App\Inventory", 'finished_by');
}
You need to add user
relationship in eager loading
$inventories = Inventory::where('company_id',$company_id)->with('user')->get();
Now Template Rendering
@foreach($inventories as $inventory)
<tr>
<td>{{$inventory->id}}</td>
<td>
@if($inventory->user)
{{$inventory->user->name}}
@else
'No User'
@endif
</td>
</tr>
@enforeach
Solution 2:[2]
Update the code of controller // you need to add the relationship
$inventories = Inventory::where('company_id',$company_id)->with('user')->get();
Solution 3:[3]
That's because you've defined users in Inventory model but you've called user in your blade file so you must change your function to:
public function user(){
return $this->belongsTo(User::class, 'finished_by');
}
Solution 4:[4]
I do not know exactly what fields you have but test this code :
@foreach($inventories as $inventory)
<tr>
<td>id : {{$inventory['id']}}</td>
<td>name : {{$inventory->users->toArray()['name']}}</td>
</tr>
@endforeach
Solution 5:[5]
$company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();
return view('inventories', compact('inventories', 'companies'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | DsRaj |
Solution 3 | Douwe de Haan |
Solution 4 | Douwe de Haan |
Solution 5 | Suraj Rao |