How to create and use a custom middleware in Laravel 9.
A middleware means that any HTTP request for that route must pass through it, making it good for checking if a user has permissions or meets a criteria etc.
For this example the middleware created will be to check if a session key has been set. If it hasn’t then redirect the user to the page where they can set this session.
With artisan create the middleware with a name
php artisan make:middleware CheckInstanceSet
This will generate:
app/Http/Middleware/CheckInstanceSet.php
Open this file and put your logic for the middleware into the handle() function
public function handle(Request $request, Closure $next)
{
if (Session::has('instance')) {
return $next($request);
}
return redirect()->route('instance.index');
}This means that if a session key for “instance” exists continue with the HTTP request else redirect to the instance set page.
Open app/Http/Kernel.php and find the $routeMiddleware array, this is where you register your middleware with the name and the class
'instance' => \App\Http\Middleware\CheckInstanceSet::class,
Finally, in your routes file assign this middleware by using the name that was used above (instance):
//Needs an instance set to view
Route::get('files', [App\Http\Controllers\FileController::class, 'index'])->middleware(['auth', 'instance']);
Route::get('actions', [App\Http\Controllers\ActionController::class, 'index'])->middleware(['auth', 'instance']);
//Does not need an instance set to view
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->middleware();
Route::get('instances', [App\Http\Controllers\InstanceController::class, 'index'])->middleware(['auth']);Since you modified your routes make sure to refresh the routes with:
php artisan route:cache
