How to Create Custom Middleware in Laravel 10
Laravel, renowned for its elegant syntax and powerful features, includes a versatile middleware system that facilitates the injection of custom code into the request lifecycle. This blog post will provide an in-depth exploration of Laravel middleware and guide you through creating a custom middleware to enhance the user experience of your web application.
1. Understanding Laravel Middleware
What is Middleware?
Middleware acts as a bridge between a request and a response. Learn how it plays a crucial role in processing HTTP requests.
How Does Middleware Work in Laravel?
Explore the inner workings of Laravel middleware and its seamless integration into the request lifecycle.
2. The Need for Custom Middleware
Enhancing User Authentication
Discover how custom middleware can augment user authentication processes for heightened security and flexibility.
Logging and Analytics
Uncover the benefits of integrating logging and analytics middleware to track user actions and gather valuable insights.
Custom Request Handling
Explore scenarios where custom request handling middleware can be a game-changer for your application.
3. Creating Your Custom Middleware
To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware EnsureTokenIsValidThis command make a new file in app/Http/Middleware directory.
Now wirte your logic in this new file in app/Http/Middleware.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
// wite your own logic insted of this example code
if ($request->input('token') !== 'my-secret-token') {
return redirect('home');
}
return $next($request);
}
}Now define your new middleware in app/Http/Kernel.php file
// app\Http\Kernel.php
protected $routeMiddleware = [
// add custom middleware after default middlewares.
'verified' => \App\Http\Middleware\EnsureTokenIsVerified::class,
];Now its a time to use our custom middleware in routes.
// routes/web.php
use App\Http\Middleware\EnsureTokenIsValid;
// you can directly use in route
Route::get('/profile', function () {
// ...
})->middleware('verified');
// OR
// you can use as group function for more than one routes
Route::middleware('verified')->group(function () {
Route::get('/', function () {
// ...
});
Route::get('/profile', function () {
// ...
})->withoutMiddleware([EnsureTokenIsValid::class]);
});By the end of this blog post, you'll not only understand the intricacies of Laravel middleware but also have practical examples to create custom middleware, adding significant value to your web applications. Let's embark on this journey to unlock the full potential of Laravel middleware!
