Laravel-permission: Filtering hasMany relationship by role

Created on 7 Jan 2019  路  4Comments  路  Source: spatie/laravel-permission

Apologies in advance if this is trivial, I am learning Laravel.

I have a simple hasMany relationship for 'Companies' and 'Users'. i.e. each company has users.

public function users()
{
    return $this->hasMany(User::class);
}

I am trying to limit the users by only those with the role 'users' (which is the same as: users without the role 'admin').

I am trying to write the relationship to filter this, but am wondering if this is possible with table joins?

public function users()
{
    return $this->hasMany(User::class)->[SOMETHING HERE TO LIMIT RESULTS BY ROLE];
}

Thanks

support

Most helpful comment

Try:

    return $this->hasMany(User::class)->role('user');

All 4 comments

Try:

    return $this->hasMany(User::class)->role('user');

Fantastic, thank you!

Can see in DebugBar that it has constructed the database queries all nicely for me.

Just what I was hoping was possible, and so clean and obvious when you know how. Thank you for the help.

For sure.
FYI - that's just a "scope". Albeit the logic is a little more complex than you're probably used to. You can see the code for it here:

https://github.com/spatie/laravel-permission/blob/0d2bd2ae84fcff084bb0f73827df985748d87b0d/src/Traits/HasRoles.php#L51-L86

So clever. Laravel makes it so clean. Thanks for the learning opportunity!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wreighsantos picture wreighsantos  路  4Comments

ergonomicus picture ergonomicus  路  3Comments

bbdangar picture bbdangar  路  4Comments

NattananWs picture NattananWs  路  3Comments

tripex picture tripex  路  3Comments