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

User1980's avatar

Best way to refactor for role checking?

Hi all,

In all my controllers and methods I have this which I find really annoying:

        $user = Auth::user();
        $roles = $user->getRoleNames();

        if(in_array($roles[0], ["admin", "super-admin"])) {

        }

        if(in_array($roles[0], ["user"])) {

        }

Is there a way to refactor this in a way where the below code is only called once and from a single area of the app?

        $user = Auth::user();
        $roles = $user->getRoleNames();

Thanks.

0 likes
6 replies
User1980's avatar

Thanks,

I am actually using this one: "spatie/laravel-permission": "3.6",

MichalOravec's avatar

@user1980 So it will work out of box, because hasAnyRole is part of that package. Why do you have a custom method getRoleNames?

User1980's avatar

Thanks, I will use this from now on then:

$user->hasAnyRole('writer', 'reader');

A lot of refactoring on the way:-)

Please or to participate in this conversation.