Eloquent many-to-many-how easy it is to transfer distance relationships

I have 3 tables; users, groups and permissions

In models, I have a relationship set as belonging to ToMany in a custom model:

public function groups() {
    return $this->belongsToMany('Group');
}

      

in the group model:

public function users() {
    return $this->belongsToMany('User');
}

public function permissions() {
    return $this->belongsToMany('Permission');
}

      

in permissions model:

public function groups() {
    return $this->belongsToMany('Group', 'id');
}

      

for many users - for many groups, many groups - for many permissions

I'm trying to get all the permissions from a user and have no idea what the code looks like for it. Can anyone please help?

+3


source to share


2 answers


Here's how you can do it:



User::where('id', $id)->with(['groups.permissions' => function ($q) use (&$permissions) {
     $permissions = $q->get()->unique();
}])->first();

// then
$permissions; // collection of unique permissions of the user with id = $id

      

+13


source


It should look something like this if you want to load ...



$user = User::where('id', $id)->with(['groups.permissions'])->first();

      

0


source







All Articles