PHPackages                             michaeljennings/route-guards - 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. michaeljennings/route-guards

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

michaeljennings/route-guards
============================

Provides a convenient place to authorize routes when model policies cannot be used

v0.1.0(5y ago)02.4kMITPHPPHP &gt;=7.2CI failing

Since May 19Pushed 5y ago1 watchersCompare

[ Source](https://github.com/michaeljennings/route-guards)[ Packagist](https://packagist.org/packages/michaeljennings/route-guards)[ RSS](/packages/michaeljennings-route-guards/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Route Guards
============

[](#route-guards)

Installation
------------

[](#installation)

To install the package run

```
composer require michaeljennings/route-guards

```

Once the package is installed, add the `MichaelJennings\RouteGuards\GuardRoutes` middleware to you `App\Http\Kernel.php`, if you are using model bindings makes ure to register it after the `SubstituteBinding` middleware.

```
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \MichaelJennings\RouteGuards\GuardRoutes::class,
    ],
];
```

Usage
-----

[](#usage)

### Registering Guards

[](#registering-guards)

You can guard a route in 3 different ways.

Firstly, you can chain a guard method on the route.

```
Route::get('/products', 'ProductController@index')->guard(ProductGuard::class);
```

Or you can set the guard in the route action.

```
Route::get('/products', ['uses' => 'ProductController@index', 'guard' => ProductGuard::class]);
```

Finally, you can specify the guard in a route group.

```
Route::group(['prefix' => 'products', 'guard' => ProductGuard::class], function () {
    Route::get('/', 'ProductController@index');
});
```

### Writing Guards

[](#writing-guards)

By default we will try to hit an authorize method on the route guard. The authorize method should return true if the user is allowed to access the route, and false if they aren't.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    public function authorize(Route $route): bool
    {
        return Auth::user()->hasPermission('products.read');
    }
}
```

Occasionally you might want to authorize one endpoint in a group differently to the others. For example, in the below routes we want to check for a different to view the products and to create a product

```
Route::group(['prefix' => 'products', 'guard' => ProductGuard::class], function () {
    Route::get('/', 'ProductController@index');
    Route::post('/', 'ProductController@store');
});
```

To do this simply add a method with the same name as the controller method to your route guard.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    public function index(Route $route): bool
    {
        return Auth::user()->hasPermission('products.read');
    }

    public function store(Route $route): bool
    {
        return Auth::user()->hasPermission('products.create');
    }
}
```

### Model Bindings

[](#model-bindings)

For certain routes you may also want to check that a user can access a specific record, for example in the route below we want to make sure the user can access a record before they can make updates to it.

```
Route::put('/products/{product}', 'ProductController@update')->guard(ProductGuard::class);
```

By default we will attempt to use model bindings to access the model from the route and pass it into the authorize method.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    // This works for authorize
    public function authorize(Route $route, Model $model): bool
    {
        // Check the user can access the model
    }

    // It also works for the custom methods
    public function update(Route $route, Model $model): bool
    {
        // Check the user can access the model
    }
}
```

### Custom Bindings

[](#custom-bindings)

If you aren't using model bindings but still want to take advantage of finding your resource in the route guard you can override the `find` method.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    public function __construct(ProductRepository $productRepository) {
        $this->productRepository = $productRepository;
    }

    // This works for authorize
    public function authorize(Route $route, Model $model): bool
    {
        // Check the user can access the model
    }

    protected function find(Route $route, string $binding)
    {
        return $this->productRepository->find(
            $route->parameter($binding)
        );
    }
}
```

### Using Multiple Guards

[](#using-multiple-guards)

In the route below we have to parameters in one route that need to be guarded differently.

```
Route::get('/products/{product}/variants/{variant}', 'Product\VariantController@show');
```

We can do this by setting two guards on the route, and telling them which parameter they guard.

```
Route::get('/products/{product}/variants/{variant}', 'Product\VariantController@show')
     ->guard(ProductGuard::class, 'product')
     ->guard(VariantGuard::class, 'variant');
```

You can also define this on a route group by providing an array where the key is the parameter the guard will protect.

```
Route::group(['prefix' => 'products/{product}/variants/{variant}', 'guards' => [
    'product' => ProductGuard::class,
    'variant' => Variant::guard
]], function () {
    Route::get('/', 'Product\VariantController@show');
});
```

### Customising Exceptions

[](#customising-exceptions)

If authorization fails we will throw the `Illuminate\Auth\Access\AuthorizationException` exception. If you want to change this you can override the `authorizationFailed` method.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    public function authorize(Route $route): bool
    {
        return false;
    }

    protected function authorizationFailed(): void
    {
        throw new CustomException();
    }
}
```

Occasionally you might want to throw a different exception for your index endpoint than your create endpoint. You can this by taking the name of the method and adding failed to it.

```
use Illuminate\Routing\Route;
use MichaelJennings\RouteGuards\RouteGuard;

class ProductGuard extends RouteGuard
{
    public function index(Route $route): bool
    {
        return false;
    }

    protected function indexFailed(): void
    {
        throw new IndexException();
    }

    public function create(Route $route): bool
    {
        return false;
    }

    protected function createFailed(): void
    {
        throw new CreateException();
    }
}
```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

2181d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/df807d0371b1b265ea1becedfa4001428f278e7632c6d175e2afb2921f5788a3?d=identicon)[michaeljennings](/maintainers/michaeljennings)

---

Top Contributors

[![michaeljennings](https://avatars.githubusercontent.com/u/5189701?v=4)](https://github.com/michaeljennings "michaeljennings (10 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/michaeljennings-route-guards/health.svg)

```
[![Health](https://phpackages.com/badges/michaeljennings-route-guards/health.svg)](https://phpackages.com/packages/michaeljennings-route-guards)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M344](/packages/tymon-jwt-auth)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M52](/packages/php-open-source-saver-jwt-auth)[laragear/two-factor

On-premises 2FA Authentication for out-of-the-box.

339785.3k8](/packages/laragear-two-factor)[codegreencreative/laravel-samlidp

Make your PHP Laravel application an Identification Provider using SAML 2.0. This package allows you to implement your own Identification Provider (idP) using the SAML 2.0 standard to be used with supporting SAML 2.0 Service Providers (SP).

263763.5k1](/packages/codegreencreative-laravel-samlidp)[webfox/laravel-xero-oauth2

A Laravel integration for Xero using the Oauth 2.0 spec

58452.0k2](/packages/webfox-laravel-xero-oauth2)

PHPackages © 2026

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