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

Pendo's avatar
Level 10

Extending Gate::allow with Entrust roles and permissions

Hi all,

I'm using Entrust (https://github.com/Zizaco/entrust) for Roles and Permissions, the package is working just fine and using the code below I was able to use Gate::allows to check for permissions from within the Entrust tables:

In AuthServiceProvider.php I added:

    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);

        foreach( $this->getPermissions() as $permission)
        {
            $gate->define($permission->name, function ($user) use ($permission) {
                return $user->can($permission->name) || $user->hasRole('owner') ;
            });
        }
    }

    /**
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getPermissions()
    {
        return Permission::with('roles')->get();
    }

This does in fact work! Howevery, this part doesn't:

return $user->can($permission->name) || $user->hasRole('owner') ;

As long as I have the permission equal to $permission->name Gate returns true. Otherwise it returns false. The code is self explaining: I want users with Role 'owner' to always have acccess to each check performed by Gate. But it seems like $user->hasRole() is not working here.

I have no clue on how to debug this, since a die-and-dump within the loop doesn't show anything.

Any ideas on how to get this working? I've been trying to get this to work for a few days already, left it for a while but I still can't seem to figure this one out.

0 likes
1 reply
Pendo's avatar
Pendo
OP
Best Answer
Level 10

Nevermind, I noticed the before() method does what I want. Totally missed that on in the docs. The solution for anyone who is interested:

    public function boot(GateContract $gate)
    {
        $gate->before(function ($user) {
            if ($user->hasRole('owner')) {
                return true;
            }
        });

        $this->registerPolicies($gate);

        foreach( $this->getPermissions() as $permission)
        {
            $gate->define($permission->name, function ($user) use ($permission) {
                return $user->can($permission->name) ;
            });
        }
    }

Please or to participate in this conversation.