Home » Php » php – Laravel Gate::any() returns reverted value

php – Laravel Gate::any() returns reverted value

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am defining gate in my code like this

    Gate::define('fullAccess',function ($user){
        return $user->id == 1;
    });
    Gate::define('manager',function ($user){
        return $user->type == User::TYPE_MANAGER;
    });

then in contoller I am checking if user has access

 public function __construct()
 {
     if(!Gate::any(['fullAccess','manager'])){
         abort(403);
     }
 }

But there is a problem:

 if(!Gate::any(['fullAccess','manager'])){
     //returns true
 }
 if(Gate::any(['fullAccess','manager'])){
     //returns false
 }

I’m absolutly sure my ID equals 1, and I think any() function must return true if at least one access action is available for curent user. Am I missing something?

I’ve tried none function also, and it works the same way

 if(Gate::none(['fullAccess','manager'])){
    //returns true;
 }
How to&Answers:

As I’ve stated in the comment, checking things in a constructor is usually not safe and can result in unexpected order of execution. The solution for the OP’s problem is to move the access check out from constructor to some controller function or elsewhere. Cheers 🙂

UPD with code example:
You override callAction method to check access before every action in controller

public function callAction($method, $parameters)
{
    if(Gate::none(['fullAccess','manager'])){
        abort(403);
    }
    return parent::callAction($method, $parameters); 
}