Search code examples
phplaravelpolicy

Problems with Laravel Policies Authorization


I really do not understand what happend. Here is my setup and code

In the UserGroupPolicy class

//Here I want to check that if $user model have group_id <= 4 
//so they cannot change group_id when editing other users

public function update(User $user, UserGroup $userGroup)
{
    return $user->group->id <= 4;
}

I registered this policy class in AuthService Provider

protected $policies = [
    'App\User' => 'App\Policies\UserPolicy',
    'App\UserGroup' => 'App\Policies\UserGroupPolicy',
    'App\Team' => 'App\Policies\TeamPolicy',
    'App\Branch' => 'App\Policies\BranchPolicy',
    'App\Company' => 'App\Policies\CompanyPolicy',
];

But when testing I have many errors occur.

In the Controller

//For testing
public function index(Request $request)
{
    //If I do not pass the user instance, like Laravel official document
    //It will throw: : Too few arguments to function
    //App\Policies\UserGroupPolicy::update(), 1 passed in 
    //path\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php
    //on line 481 and exactly 2 expected

    var_dump($request->user()->can('update', UserGroup::class));

    //if I pass, it will always return true although I edit the update function
    //in UserGroupPolicy class just return false
    var_dump($request->user()->can('update', $request->user(), UserGroup::class));

}

So can anyone help me, thank you.


Solution

  • Try using

    $this->authorize('update',UserGroup::class);
    

    instead of

    $request->user()->can('update', UserGroup::class);
    

    UPDATE:The second argument must be an instance of the UserGroup class and not the UserGroup class itself.So the correct code is

     $this->authorize('update',$objectOfUserGroupClass);//and not the class itself
    

    For more info check here

    It works for me....