Search code examples
laravellaravel-permission

How to use spatie permission middleware in Laravel?


I am using Laravel 8 and Spatie Role and Permission. Permission for each action working fine. But if i assign delete action permission to sub admin but I hit create action directly from URL middlware can not stop action as user have not create permission.

 public function __construct(CustomerInterface $customerInterface)
{
    $this->customerInterface = $customerInterface;
    $this->middleware(['permission:create_customer|delete_customer|edit_customer|chnage_customer_status']);
}

I am using above middleware in constructor. How can i Solve this issue.


Solution

  • From what I can tell from the documentation, when you use the permission middleware with multiple permissions, it will let the request proceed if at least one permission checks out.

    What you need is method-based authorization and for that, Laravel uses policies which by default lets you write separate authorization for common methods. (index, store, update, show, etc)

    Let's say you let a user use the store method only if they have the create_customer permission, your policy will look something like this:

        /**
         * Determine whether the user can create models.
         *
         * @param User $user
         * @return mixed
         */
        public function create(User $user)
        {
            return $user->can('create_customer');
        }
    

    Then in your controller, you put the authorizeResource function which associates the default policy methods with your default resource controller methods:

        public function __construct(CustomerInterface $customerInterface)
        {
            $this->customerInterface = $customerInterface;
            $this->authorizeResource(Customer::class); // assuming your model name is Customer
        }
    

    alternatively, you can write your own custom policy methods and use them via the $this->authorize method which is documented further here.