laravelerror-handlingrelationships

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

  • 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