Middleware in Laravel acts as a bridge between a request and a response, allowing you to inspect and filter HTTP requests entering your application. While Laravel provides several built-in middleware, creating custom middleware can help tailor request handling to your application's specific needs.([techsolutionstuff][1])
In this tutorial, we'll walk through creating a simple custom middleware that restricts access to certain routes based on a user's age.
Step 1: Generate the Middleware
Use Laravel's Artisan command to create a new middleware class:
php artisan make:middleware CheckAge
This command creates a new file at app/Http/Middleware/CheckAge.php
.
Step 2: Implement the Middleware Logic
Open the newly created CheckAge.php
file and define the logic to check the user's age:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
public function handle(Request $request, Closure $next)
{
if ($request->age < 18) {
return response('Access denied: You must be at least 18 years old.', 403);
}
return $next($request);
}
}
This middleware checks if the age
parameter in the request is less than 18. If so, it returns a 403 response; otherwise, it allows the request to proceed.([Wikipedia][3])
Step 3: Register the Middleware
To use the middleware, register it in the app/Http/Kernel.php
file by adding it to the $routeMiddleware
array:
php
protected $routeMiddleware = [
// ...
'check.age' => \App\Http\Middleware\CheckAge::class,
];
Step 4: Apply the Middleware to Routes
Now, you can apply the middleware to specific routes in your routes/web.php
file:
use Illuminate\Support\Facades\Route;
Route::get('/restricted', function () {
return 'Welcome to the restricted section.';
})->middleware('check.age');
When accessing the /restricted
route, include an age
parameter in the query string (e.g., /restricted?age=20
). If the age is less than 18, the middleware will deny access.
Testing the Middleware
Start your Laravel development server:
Then, test the middleware by visiting:
http://localhost:8000/restricted?age=17
– Should return "Access denied: You must be at least 18 years old."
http://localhost:8000/restricted?age=20
– Should return "Welcome to the restricted section."
Conclusion
Creating custom middleware in Laravel allows you to encapsulate request filtering logic, making your application more modular and maintainable. Whether it's for authentication, logging, or custom access control, middleware provides a clean way to manage HTTP request handling.
Feel free to experiment with more complex conditions and explore how middleware can enhance your Laravel applications!
Happy coding! If you found this tutorial helpful, consider sharing it with your fellow developers.