DEV Community

Cover image for How to Create a Custom Dynamic Middleware for Spatie Laravel Permission
Code And Deploy
Code And Deploy

Posted on

How to Create a Custom Dynamic Middleware for Spatie Laravel Permission

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/how-to-create-a-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
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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
];
Enter fullscreen mode Exit fullscreen mode

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
    });
});
Enter fullscreen mode Exit fullscreen mode

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

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/how-to-create-a-custom-dynamic-middleware-for-spatie-laravel-permission if you want to download this code.

Happy coding :)

Top comments (1)

Collapse
 
krismawan_riki profile image
🌟 NewFolder

Nice