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?
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
}
@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
@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
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.
Please sign in or create an account to participate in this conversation.