Table of contents
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 :)
Read next