Table of contents

custom dynamic middleware for spatie laravel permission

In this post, I'm sharing how to create a custom middleware for spatie Laravel permission. In my previous post, I shared how to implement the Laravel 8 user roles and permissions using spatie. Now I let's do a separate post about how to create custom middleware for your permission.

 

So if you want to create a custom dynamic middleware permission this is for you. Let's use your route name as permission in this tutorial.

 

Please visit my previous post if you need it.

 

To shorten, I assumed that you already install the Laravel permission by spatie.

 

Step 1: Create a Middleware

Run the following command to your project directory:

php artisan make:middleware PermissionMiddleware

 

And here is the custom code of our PermissionMiddlware class. Navigate to App\Http\Middleware\PermissionMiddleware.php

 

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\UnauthorizedException;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $permission = null, $guard = null)
    {
        $authGuard = app('auth')->guard($guard);

        if ($authGuard->guest()) {
            throw UnauthorizedException::notLoggedIn();
        }

        if (! is_null($permission)) {
            $permissions = is_array($permission)
                ? $permission
                : explode('|', $permission);
        }

        if ( is_null($permission) ) {
            $permission = $request->route()->getName();

            $permissions = array($permission);
        }
        

        foreach ($permissions as $permission) {
            if ($authGuard->user()->can($permission)) {
                return $next($request);
            }
        }

        throw UnauthorizedException::forPermissions($permissions);
    }
}

 

Step 2: Register Custom Middleware

After generated and added the code to your middleware let's register it.

 

Now let's navigate file app/Http/Kernel.php then in the $routeMiddleware property we will add the following middlewares.

 

protected $routeMiddleware = [
        .
        .
        'permission' => \App\Http\Middleware\PermissionMiddleware::class
];

 

Now our custom dynamic permission is registered already. Let's put it to restricted routes.

 

Step 3: Add Routes

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['namespace' => 'App\Http\Controllers'], function()
{   
  
    Route::group(['middleware' => ['auth', 'permission']], function() {
      //your restricted routes here
    });
});

 

As you can see we added the 'permission' middleware to our restricted group routes.

 

That's it. I hope it helps.

 

Thank you for reading :)