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.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

Nice and clear tutorial—great job explaining each step! Quick question: how would you handle cases where the age parameter isn’t provided at all in the request? Would you set a default, show an error, or redirect?

Honestly, that's a great question—and a common scenario developers face when working with middleware in Laravel. If the age parameter isn't provided in the request, it's essential to handle it gracefully to ensure your application remains robust and user-friendly.

In such cases, setting a default value for the age parameter is a practical approach. This ensures that your middleware has a value to work with, even if the user doesn't provide one. For example, you can default the age to 0, which would typically fail the age check and deny access:

$age = $request->input('age', 0); // Defaults to 0 if 'age' is missing
This way, your middleware remains robust and handles missing parameters gracefully.

Alternatively, you might consider:

Returning an error response indicating that the age parameter is required.

Redirecting the user to a specific page, such as an age verification form.

Each of these methods has its use cases, and the best choice depends on the specific requirements and user experience goals of your application.

But then, I haven't rally needed to think much about it.
I just add validation errors directly in the controller methods that receives the request

More Posts

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

Laravel 12 & Laravel Cloud: The Next Big Leap in Web Development

Snehal Kadwe - Mar 9

Using Bash to Monitor Server Health (CPU, RAM, Disk) – A Beginner-Friendly Guide

Gift Balogun - May 25
chevron_left