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

SCC's avatar
Level 7

Cycle through roles to verify if one exists

Going back to this video https://laracasts.com/lessons/users-and-roles

I have everything working as it should. In my roles table I have 7 roles and have assigned all of them to only current user.

I need therefore to create a new

public function isAdmin()
{
....
}

to return true if one of those 7 roles is "Administrator". How would I do that? Is it best to cycle through with a foreach or use collections?

0 likes
4 replies
mstnorris's avatar
Level 55

Yeah you could do


    public function isA($roleName)
    {
        foreach ($this->roles()->get() as $role)
        {
            if ($role->name == $roleName)
            {
                return true;
            }
        }

        return false;
    }

Then, for checking isAdmin specifically you can just call

public function isAdmin()
{
    return $this->isA('Administrator'); // or whatever other role you would like to check for
}
1 like
SCC's avatar
Level 7

@mstnorris thanks, makes sense, I am sure collections could have a part to play however I am more comfortable with the foreach way.

Cheers!

Lee

alexwolff's avatar

@HC-Lee This should work as well.

Maybe a little cleaner

public function isA($roleName)
    {
        return ($this->roles()->whereName($roleName)->get()) ? true:false;
    }

I assume your roles table has a name column. Otherwise replace the whereName part.

Alex

mstnorris's avatar

I am sure too, but don't forget that you can optimise in the future, if it works right now then do it. There is no harm. Don't get caught up in early-optimisations.

1 like

Please or to participate in this conversation.