Search code examples
phpmysqllaraveleloquentrelationships

Display in VIEW of One to One relation in Laravel Relationship


I am here again with a trouble understanding the correct way of doing Laravel Relationships

I have this User Model

 public function concessionaire()
{
    return $this->hasOne('App\Concessionaire', 'meternum', 'meternum');
}

and Concessionaire Model

 public function user()
{
    return $this->belongsTO('App\User', 'meternum', 'meternum');
}

But when I try to display it in my view. the concessionaire data fields does not display..

In my Controller I have this

$dataUser = User::where('usertype', '=', 'concessionaire')
                ->with('concessionaire')
                ->get();
    return view('admin.concessionaire',compact('dataUser'));

in my View

@foreach($dataUser as $User)
<td>
{{ $User->clark }}
</td>
@endforeach

Solution

  • first please check the foreign and local key's are correct in the relation function implementation. after that try dumb the data like

    dd($dataUser )
    

    and check whether the user model's relations attributes actually contains the relationship model if its not empty you can access the property like

    $User->concessionaire->property
    

    if the relations attributes shows empty then you might have put incorrect local or foreign keys in the relationship implementation function.

    you should follow

    $this->hasOne(Relation::class, 'foreign key in related model', 'local key')