Search code examples
laravellaravel-5laravel-5.5laravel-5.6

Laravel - Using Gate::allows for multiple objects


Is there a way to validate a policy for multiple elements or ids?

Let's say I have a $user object.

I can do: \Gate::allows('delete', $user).

What if I have a collection of User objects: $users.

Is there a way to do \Gate::allows('delete', $users)?

EDIT:

I have a route for deleting multiple entities.

Route::delete('/users', 'UsersController@deleteMultiple');

The payload is an array of ids.

['ids' => [1, 2, 3]]


Solution

  • When you define a Gate in Laravel, you can pass any number of arguments to the closure. The only requirement is that the first parameter accepts a $user argument, which is the currently authenticated user. Any additional parameters you define are completely up to you. You could easily write a Gate that authorizes bulk delete functionality like this:

    Gate::define('bulk-delete', function ($user, Collection $users) {
        // Your logic may differ
        return $users->every(function ($subject) use ($user) {
            return $user->canDelete($subject);
        });
    });
    

    Then, in your controller or service class, you can write the following:

    if (Gate::allows('bulk-delete', $users)) {
        // The current user can bulk delete the users...
    }
    

    Of course, you will probably want to refactor this to a Policy class for better maintainability.