Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 4 months ago.
0

Because the relationship will be returned as a collection you can use some handy array utilities on the collection items to check if the user has a given role. You might like to make a hasRole method on the User model, it would make things look nicer.

public function hasRole($id)
{
    return ! $this->roles->filter(function($role) use ($id)
    {
        return $role->id == $id;
    })->isEmpty();
}

And then...

if ($user->hasRole(3))
{
    // User is an admin.
}

The hasRole method uses filter to remove any roles that don't have the ID that is given to the method. Then you can use isEmpty on the newly returned collection to see if there were any roles. If it isn't empty then the user has that role.

Of course role management can be made easier by implementing some form of ACL, like Authority: https://github.com/machuga/authority-l4

There's a couple of different packages out there that make dealing with roles and permissions a breeze.

Last updated 4 months ago.
0

Thanks, that should do it. That is what I was envisioning but I figured I was overlooking something that was built-in. Thanks for the tips on user roles as well, but like I said, I was just using that as an example because it is used in the docs.

Last updated 4 months ago.
0

what about

$roles = User::find(1)->roles;

if ($roles->contains(2))
{
    //
}

source: http://laravel.com/docs/eloquent#collections

although in all honesty I like Jason's answer better

Last updated 4 months ago.
0

Sign in to participate in this thread!

Full Stack Europe

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.