Middleware in Laravel is used to filter requests to a page. It is mostly used for authentication and security. A useful example of middleware is the process of being logged in. On each page that requires user authentication, a middleware request is sent out to verify that user indeed has authentication.
By default, Laravel already includes several Middleware classes avaliable to use, including one for authentication. You can create additional classes by using the following artisan command:
php artisan make:middleware {name}
Once the command is executed, you will have an empty middleware class with a handle function created. The class should be located in app/Http/Middleware
in your project directory.
To allow the middleware to be used globally (so that it will run before every HTTP request), you will need to add the new Middleware class to the $middleware
property in your Kernel class. This can be found in app/Http/kernal.php
.
protected $routeMiddleware = [
/* ... */
'Name' => \App\Http\Middleware\Name::class,
];
Once the middleware is defined in the kernal, it can be used in a Route:
Route::get('/', 'Controller@method')->middleware('Name');