Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent many-to-many-to-many - how to load distant relation easily

I have 3 tables; users, groups and permissions

In models I have the relationships set as belongsToMany in user model:

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

in 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');
}

many users - to - many groups many groups - to - many permissions

I'm trying to get all the permissions a user has, and have no clue what the code for it should look like. Can anyone help?

like image 931
Pawel Bieszczad Avatar asked Dec 12 '22 03:12

Pawel Bieszczad


1 Answers

This is 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
like image 159
Jarek Tkaczyk Avatar answered Feb 01 '23 22:02

Jarek Tkaczyk