phplaravelauthorizationlaravel-8laravel-gate

Gate not allows user while he has already that permission


I'm working with Laravel 8.5 and I wanted to develop my own ACL.

So I made this ManyToMany relationship between Permission & User models:

User.php:

public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }

Permission.php:

public function users()
    {
        return $this->belongsToMany(User::class);
    }

Then I have inserted this custom permission into permissions table:

enter image description here

And then inserted this also into the pivot table pemrission_user:

enter image description here

Then at web.php, I tried this:

Route::get('/', function () {
    $user = auth()->user();
    // dd($user->permissions()->get());
    if(Gate::allows('edit-user')){
        dd(2);
    }else{
        dd(1);
    }
});

So I tried checking if the logged in user has the permission edit-user, then shows 2 as result but now it returns 1 somehow, meaning that user has not this permission!

However if I uncomment dd($user->permissions()->get());, I can see this:

enter image description here

So as it shows user already has this edit-user permission but I don't why the Gate does not authorize user in this case.

So if you know, I beg you to help me cause I really don't know how to solve this...


Solution

  • You need to define edit-user for your Gate as well because your permission model means nothing to the Gate at the moment.

    Gate::define('edit-user', function (User $user) {
        return $user->permissions()->whereName('edit-user')->exists();
    });
    

    More information can be found here: https://laravel.com/docs/8.x/authorization#writing-gates


    Otherwise, you can use policies:

    class UserPolicy
    {
        public function update(User $user)
        {
            return $user->permissions()->whereName('edit-user')->exists();
        }
    }
    

    And then to allow the user:

    $user->can('update', User::make());
    

    More information about policies can be found here: https://laravel.com/docs/master/authorization#creating-policies


    There's also an open source package called laravel-permission made by Spatie that you can have a look at to learn more.