In Laravel, middleware is a way to filter HTTP requests entering your application. It provides a convenient mechanism for filtering HTTP requests entering your application. Laravel includes a variety of middleware like Authenticate
, Authorize
, EncryptCookies
, and more, and you can also create your own custom middleware.
Here's a step-by-step guide on how to use middleware in Laravel:
1. Applying Middleware to Routes:
Middleware can be applied to specific routes or groups of routes in your routes/web.php
or routes/api.php
file.
Route::get('/example', 'ExampleController@index')->middleware('middlewareName'); |
2. Applying Middleware to Controller Actions:
You can also apply middleware directly to controller actions.
class ExampleController extends Controller { public function __construct() { $this->middleware('middlewareName'); } public function index() { // Controller action logic } } |
3. Applying Middleware to Route Groups:
Middleware can be grouped and applied to multiple routes at once.
Route::middleware(['middlewareName'])->group(function () { // Routes that use the middleware }); |
Creating Custom Middleware:
1. Generate Middleware:
Run the following command to generate a new middleware class:
php artisan make:middleware CustomMiddleware |
This will create a new middleware class in the app/Http/Middleware
directory.
2. Edit the Middleware:
Open the generated middleware file (CustomMiddleware.php
) and implement the handle
method.
<?php namespace App\Http\Middleware; use Closure; class CustomMiddleware { public function handle($request, Closure $next) { // Perform actions before the request is handled $response = $next($request); // Perform actions after the request is handled return $response; } } |
3. Register the Middleware:
Add your middleware to the $routeMiddleware
array in the app/Http/Kernel.php
file.
protected $routeMiddleware = [ // Other middleware... 'custom' => \App\Http\Middleware\CustomMiddleware::class, ]; |
4. Apply the Middleware:
You can now apply your custom middleware to routes or controllers using the name you provided in the $routeMiddleware
array.
Route::get('/example', 'ExampleController@index')->middleware('custom'); |
Now, when a request is made to the specified route or controller, your middleware will be executed, and you can perform any necessary actions before or after the request is handled.
=== Happy Coding :)