Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use spatie/laravel-authorize with both gates and policies


Can I use spatie/laravel-authorize with both gates and policies


Yes, you can use the `spatie/laravel-authorize` package with both gates and policies in your Laravel application.

The `spatie/laravel-authorize` package is designed to work seamlessly with Laravel's built-in authorization system, which includes both gates and policies.

Here's how you can use the package with both gates and policies:

1. Define Gates:
You can define your application's gates in the `boot` method of your `AuthServiceProvider`, just as you would without the `spatie/laravel-authorize` package.

php
   // app/Providers/AuthServiceProvider.php
   public function boot()
   {
       $this->registerPolicies();

       Gate::define('view-dashboard', function ($user) {
           return $user->isAdmin();
       });
   }
   

2. Define Policies:
You can also define your application's policies in the same `AuthServiceProvider`, and the `spatie/laravel-authorize` package will automatically recognize and use them.

php
   // app/Providers/AuthServiceProvider.php
   protected $policies = [
       Post::class => PostPolicy::class,
   ];
   

3. Use the `can` Middleware:
With the `spatie/laravel-authorize` package, you can use the `can` middleware to protect your routes, just as you would with Laravel's built-in authorization system.

php
   // routes/web.php
   Route::get('/dashboard', [DashboardController::class, 'index'])
       ->middleware('can:view-dashboard');

   Route::put('/posts/{post}', [PostController::class, 'update'])
       ->middleware('can:update,post');
   

In the first example, the `view-dashboard` gate is used to authorize the user. In the second example, the `update` method of the `PostPolicy` is used to authorize the user's access to the `update` action.

The `spatie/laravel-authorize` package will automatically handle the authorization checks, whether you're using gates or policies, and it will throw the appropriate `UnauthorizedException` if the user is not authorized to perform the action.

You can then customize the exception handling in your application's `app/Exceptions/Handler.php` file, as shown in the previous responses, to provide a user-friendly response for unauthorized access attempts.

By using both gates and policies in your application, you can leverage the strengths of each approach to create a comprehensive and flexible authorization system that meets the specific needs of your application.

Citations:
[1] https://packagist.org/packages/spatie/laravel-authorize
[2] https://laravel.com/docs/11.x/authorization
[3] https://laravel-news.com/laravel-gates-policies-guards-explained
[4] https://spatie.be/docs/laravel-permission/v6/advanced-usage/exceptions
[5] https://www.twilio.com/en-us/blog/what-are-laravel-policies-and-how-to-use-them-to-control-access