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:
And then inserted this also into the pivot table pemrission_user
:
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:
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...
You need to define
edit-user
for your Gate as well because your permission model means nothing to the Gate at the moment.More information can be found here: https://laravel.com/docs/8.x/authorization#writing-gates
Otherwise, you can use policies:
And then to allow the user:
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.