PHPackages                             spatie/laravel-authorize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. spatie/laravel-authorize

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

spatie/laravel-authorize
========================

A middleware to check authorization

1.1.2(9y ago)20125.8k↓50%191MITPHPPHP &gt;=5.5.0

Since Sep 22Pushed 3mo ago6 watchersCompare

[ Source](https://github.com/spatie/laravel-authorize)[ Packagist](https://packagist.org/packages/spatie/laravel-authorize)[ Docs](https://github.com/spatie/laravel-authorize)[ RSS](/packages/spatie-laravel-authorize/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (5)Versions (9)Used By (1)

A middleware to check authorization
===================================

[](#a-middleware-to-check-authorization)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d8e0720ed772d343daa7a6a386a976bd95e5f660d0cff98f64e4f2e2f7c9dc32/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d617574686f72697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-authorize)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/e7d1f4f415a26b095726262344c2e43fb34e8f1c47b06f7d9c03bd97417d33e7/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f6c61726176656c2d617574686f72697a652f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/laravel-authorize)[![SensioLabsInsight](https://camo.githubusercontent.com/c258f84a055763ab40e369d39052c323edc85cf962eaf8442f24166700aef2f6/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f63366164663437382d393962392d346135322d383633352d3838316636623636633864332e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/c6adf478-99b9-4a52-8635-881f6b66c8d3)[![Quality Score](https://camo.githubusercontent.com/dd2ec4b2e3f241847edadab58e47f5c93be306d6943781f9aa8e4f1cd9f41f08/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f6c61726176656c2d617574686f72697a652e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/laravel-authorize)[![StyleCI](https://camo.githubusercontent.com/dff82d9f39f1333c1c22355b159bb69493336c83ef1aed5d7ff334b9f9e337c3/68747470733a2f2f7374796c6563692e696f2f7265706f732f34323839363132302f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/42896120)[![Total Downloads](https://camo.githubusercontent.com/808fb040f2e09e32d43459639c1f9f77068d1a8adbb9c868d88d756b92ed9e1e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d617574686f72697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-authorize)

This package provides a route middleware to protect routes from unauthorized access. It hooks into the authorization features that were [introduced in Laravel 5.1.11](http://laravel.com/docs/5.1/authorization).

Protecting a route can be done by adding middleware to it:

```
Route::get('/top-secret-page', [
   'middleware' => 'can:viewTopSecretPage',
   'uses' => 'TopSecretController@index',
]);
```

Of course this middleware can also be applied to a bunch of routes:

```
Route::group(['prefix' => 'admin', 'middleware' => 'can:viewAdmin'], function() {

   //all the controllers of your admin section
   ...

});
```

Furthermore the middleware can use [route model binding](https://laracasts.com/series/laravel-5-fundamentals/episodes/18):

```
Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => 'PostController@edit',
]);
```

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/ac4b761d4518dd324d923b765679d119b6fe23bfa7d34567b38c291623add1a3/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d617574686f72697a652e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-authorize)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Postcardware
------------

[](#postcardware)

You're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment you are required to send us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

The best postcards will get published on the open source page on our website.

Do not use in Laravel 5.2.28 and up
-----------------------------------

[](#do-not-use-in-laravel-5228-and-up)

Laravel 5.2.28 or higher contain the middleware this package provides [out of the box](https://github.com/laravel/framework/blob/v5.2.28/src/Illuminate/Foundation/Http/Middleware/Authorize.php). There's no need do install this package in those versions of Laravel.

Install
-------

[](#install)

You can install the package via composer:

```
$ composer require spatie/laravel-authorize
```

Next, you must install the service provider:

```
// config/app.php
'providers' => [
    ...
    Spatie\Authorize\AuthorizeServiceProvider::class,
];
```

Next, the `\Spatie\Authorize\Middleware\Authorize::class`-middleware must be registered in the kernel:

```
//app/Http/Kernel.php

protected $routeMiddleware = [
  ...
  'can' => \Spatie\Authorize\Middleware\Authorize::class,
];
```

Naming the middleware `can` is just a suggestion. You can give it any name you'd like.

The `authorize`-middleware includes all functionality provided by the standard `auth`-middleware. So you could also opt to replace the `App\Http\Middleware\Authenticate`-middleware by `Spatie\Authorize\Middleware\Authorize`:

```
//app/Http/Kernel.php

protected $routeMiddleware = [
    'auth' => 'Spatie\Authorize\Middleware\Authorize',
    ...
];
```

You can publish the config-file with:

```
php artisan vendor:publish --provider="Spatie\Authorize\AuthorizeServiceProvider"
```

This is the contents of the published config file:

```
return [
    /*
     * The path to redirect for login.
     */
    'login_url' => 'auth/login'
];
```

Usage
-----

[](#usage)

### Checking authentication

[](#checking-authentication)

When the middleware is used without any parameters at all, it will only allow logged in users to use the route. If you plan on using the middleware like this I recommend that you replace the standard `auth`-middleware with the one provided by this package.

```
//only logged in users will be able to see this

Route::get('/top-secret-page', ['middleware' => 'auth', 'uses' => 'TopSecretController@index']);
```

### Checking authorization

[](#checking-authorization)

The middleware accepts the name of an ability you have defined as the first parameter:

```
//only users with the viewTopSecretPage-ability be able to see this

Route::get('/top-secret-page', [
   'middleware' => 'can:viewTopSecretPage',
   'uses' => 'TopSecretController@index',
]);
```

### Using form model binding

[](#using-form-model-binding)

Image you've set up an ability like this:

```
//inside the boot method of AuthServiceProvider

$gate->define('update-post', function ($user, $post) {
    return $user->id === $post->user_id;
});
```

The middleware accepts the name of a bound model as the second parameter.

```
Route::get('/post/{post}', [
   'middleware' => 'can:editPost,post',
   'uses' => 'PostController@edit',
]);
```

Behind the scene the middleware will pass the model bound that is bound to the round to the defined `update-post`-ability.

What happens with unauthorized requests?
----------------------------------------

[](#what-happens-with-unauthorized-requests)

### Default behaviour

[](#default-behaviour)

This is the default behaviour defined in the middleware.

```
use Symfony\Component\HttpKernel\Exception\HttpException;
...

protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
{
    if ($request->ajax()) {
        return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);
    }

    if (!$request->user()) {
        return redirect()->guest(config('laravel-authorize.login_url'));
    }

    throw new HttpException(Response::HTTP_UNAUTHORIZED, 'This action is unauthorized.');
}
```

So guests will get redirected to the default login page, logged in users will get a response with status `HTTP_UNAUTHORIZED` aka 401.

### Custom behaviour

[](#custom-behaviour)

To customize the default behaviour you can easily extend the default middleware and override the `handleUnauthorizedRequest`-method. Don't forget to register your class at the kernel.

If you would like to let all unauthorized users know that you are actually a teapot you can do so.

```
//app/Http/Middleware/Authorize.php

namespace App\Http\Middleware;

use Spatie\Authorize\Middleware\Authorize as BaseAuthorize;
use Symfony\Component\HttpFoundation\Response;

class Authorize extends BaseAuthorize
{
    protected function handleUnauthorizedRequest($request, $ability = null, $model = null)
    {
        return reponse('I am a teapot.', Response::HTTP_I_AM_A_TEAPOT);
    }
}
```

In the kernel:

```
//app/Http/Kernel.php

  protected $routeMiddleware = [
        'can' => 'App\Http\Middleware\Authorize',
        ...
    ];
```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Testing
-------

[](#testing)

This package contains integration tests that are powered by [orchestral/testbench](https://github.com/orchestral/testbench).

You can run all tests with:

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

A big thank you to [Joseph Silber](https://github.com/JosephSilber) for all the excellent feedback he gave while this package was being created.

About Spatie
------------

[](#about-spatie)

Spatie is webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance54

Moderate activity, may be stable

Popularity44

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 83.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~81 days

Recently: every ~101 days

Total

6

Last Release

3480d ago

Major Versions

0.0.1 → 1.0.02015-09-23

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (69 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (3 commits)")[![canvural](https://avatars.githubusercontent.com/u/1574232?v=4)](https://github.com/canvural "canvural (1 commits)")[![finagin](https://avatars.githubusercontent.com/u/11045296?v=4)](https://github.com/finagin "finagin (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

---

Tags

authorizationlaravelmiddlewarephpsecuritymiddlewarespatielaravelauthorizationroutelaravel-authorize

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/spatie-laravel-authorize/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-authorize/health.svg)](https://phpackages.com/packages/spatie-laravel-authorize)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[santigarcor/laratrust

This package provides a flexible way to add Role-based Permissions to Laravel

2.3k5.4M43](/packages/santigarcor-laratrust)[spatie/laravel-login-link

Quickly login to your local environment

4381.2M1](/packages/spatie-laravel-login-link)[spatie/laravel-passkeys

Use passkeys in your Laravel app

444494.4k16](/packages/spatie-laravel-passkeys)[spatie/laravel-one-time-passwords

Use one-time passwords (OTP) to authenticate in your Laravel app

170223.1k3](/packages/spatie-laravel-one-time-passwords)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
