php – Laravel eloquent relationship chaining-ThrowExceptions

Exception or error:

I have three table shares, share_users, users structure as follows –

users ( Table ) -
     -id
     -name
     -email

shares( Table ) -
     -id
     -name

share_users - 
     -id
     -user_id
     -share_id

I want to retrieve user data from share model using Laravel eloquent relations.

Thanks in advance.

How to solve:

If you define the many to many relationship to the User model in the Share model correctly, as described at https://laravel.com/docs/master/eloquent-relationships, you will be able to retrieve the users for a share easily.

add to Share model:

public function users()
{
    return $this->belongsToMany(App\User::class, 'share_users');
}

Consumption:

$share = Share::find(1);

foreach($share->users as $user) {
 dump($user);
}

Leave a Reply

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