Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theProfit's avatar

Trough pivots manyToMany

Hi All,

I have a question i have a users table a roles table and a rights table.

now the user can have multi roles witch i have so

$user::find(1); $user->roles

so every role can have multi rights

so i want to make a user with 2 roles and 10 rights, how can i make a function it will return all the rights like a collection?

0 likes
2 replies
kevinbui's avatar

I assume you have the following models and relationships. I think the allRights method can achieve your results.

class User extends Authenticatable
{
    public function roles()
    {
        $this->belongsToMany(Role::class);
    }

    public function allRights()
    {
        return $this->roles
            ->flatMap->rights
            ->unique('id');
    }
}

class Role extends Model
{
    public function rights()
    {
        $this->belongsToMany(Right::class);
    }
}

Please or to participate in this conversation.