Laravel Middleware: How To Craft Your Own HTTP Gatekeepers.

Laravel Middleware: How To Craft Your Own HTTP Gatekeepers.

●2 ●4 ●9
calendar_today • schedule2 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
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

A Message From Our Founder: On the Winding Down of LaaSy™

Ken W. Algerverified - Oct 29
chevron_left
208 Points • 15 Badges
2Posts
3Comments
I am a laravel php, reactJs and expressJS developer.
I am also a data analyst.

Related Jobs

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!