Laravel Middleware: How To Craft Your Own HTTP Gatekeepers.

Laravel Middleware: How To Craft Your Own HTTP Gatekeepers.

posted 2 min read

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:

  • php artisan serve

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.

4 Comments

1 vote
1 vote
1 vote
1 vote

More Posts

Building a Rate-Limiting Middleware for Your API in Laravel

Gift Balogun - Oct 8

How to Create a Custom Artisan Command in Laravel

Darlington Okorie - May 11

Laravel is How Development Should Be

psypher1 - Mar 31

Implement Your Own Request Middleware for Go HTTP Server

didikts - May 4

Mastering Laravel Task Scheduling for Automated Jobs (Compatible with Laravel 10, 11 & 12)

Gift Balogun - Oct 29
chevron_left