Skip to content
Advertisement

Laravel 5 : how to acces in a field on the hasMany table?

i have two models linked with hasMany to many relationship and there are my tables structure

clients = id|title...etc
roles = id|title...etc
client_role = id|client_id|role_id|desc

everythings works great now i want to access to the desc field on the client_role table how can i do that? i tried

$client =  Client::first()->roles()->desc 
//nothing returned!
$client =  Client::first()->desc 

but nothing ! please help

Advertisement

Answer

You have to load the columns of your pivot in the model relationship (Clients, for example):

return $this->belongsToMany('AppRole')->withPivot('desc');

Then you can call the column in the pivot like this:

foreach ($clients as $client) {
    echo $client->pivot->desc;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement