Creating custom middleware in Laravel 11 allows you to intercept requests entering your application and perform actions before or after passing them to the controller. This is particularly useful for tasks like authentication, logging, or manipulating requests and responses. Let’s delve into creating custom middleware in Laravel 11.
To create a custom middleware, follow these steps:
- Generate the Middleware:
You can use the artisan command-line tool to generate a new middleware. Open your terminal and run:
php artisan make:middleware CustomMiddleware
This command will create a new middleware class in the app/Http/Middleware
directory.
- Implement the Middleware Logic:
Open the newly created middleware class,CustomMiddleware.php
. In thehandle()
method, you can define the logic that should be executed for each incoming request. For instance, if you want to check if the user is authenticated, you can add authentication logic here.
<?php
namespace App\Http\Middleware;
use Closure;
class CustomMiddleware
{
public function handle($request, Closure $next)
{
// Perform actions before passing the request to the controller
// Check if user is authenticated
if (!auth()->check()) {
return redirect()->route('login');
}
return $next($request);
}
}
- Register the Middleware:
After implementing your middleware logic, you need to register it in the$routeMiddleware
array within theapp/Http/Kernel.php
file. Add an entry with a key and the fully qualified class name of your middleware.
protected $routeMiddleware = [
// Other middleware entries...
'custom' => \App\Http\Middleware\CustomMiddleware::class,
];
- Apply Middleware to Routes:
You can apply the custom middleware to routes or groups of routes by using themiddleware()
method within your route definitions inroutes/web.php
orroutes/api.php
.
Route::get('/dashboard', function () {
// Your route logic...
})->middleware('custom');
- Testing the Middleware:
Finally, test your middleware to ensure it behaves as expected. Send requests to the routes where you applied the middleware and verify that it’s working correctly.
In summary, creating custom middleware in Laravel 11 involves generating the middleware class, implementing the logic in the handle()
method, registering it in the kernel, applying it to routes, and testing its functionality. By following these steps, you can efficiently integrate custom functionality into your application’s request lifecycle.