php – Laravel 5 : how to acces in a field on the hasMany table?-ThrowExceptions

Exception or error:

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

How to solve:

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

return $this->belongsToMany('App\Role')->withPivot('desc');

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

foreach ($clients as $client) {
    echo $client->pivot->desc;


In your Clients model have:

public function roles() {
    return $this->belongsToMany('App\Clients');

In your Roles model have:

public function clients() {
    return $this->belongsToMany('App\Roles');

Then from your controller:

$client =  Client::with('roles')->first();
dd($client->roles); // Laravel Collection

Leave a Reply

Your email address will not be published. Required fields are marked *