Laravel Middleware Gatekeeper?

Laravel Middleware Gatekeeper?

Laravel
PHP

1. What is Middleware in Laravel?

You can think of middleware as a "gatekeeper" for every incoming request to your Laravel application.

Whenever a user sends a request (e.g., visiting the /dashboard page), Laravel first checks if that request should be passed on to the Controller or if it should be rejected/redirected. So, middleware is a layer of logic that runs before (or after) a request reaches the controller. Real-world examples of built-in Laravel middleware:

  • auth → ensures the user is logged in.
  • verified → ensures the user has verified their email.
  • throttle → limits the number of requests (rate limiting).

2. How Does It Work?

The simple flow is: User Request → Middleware → Controller → Response

For example:

  1. A user tries to access /dashboard.
  2. The auth middleware checks: "Is the user logged in?"
  3. If yes → the request is passed on to the Controller.
  4. If no → the user is redirected to the login page.

3. How to Create Middleware

  1. Generate the Middleware
php artisan make:middleware CheckAge

This command creates a new file at app/Http/Middleware/CheckAge.php.

  1. Fill in the Middleware Logic
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->age < 18) {
            return redirect('home'); // reject if age < 18
        }

        return $next($request); // proceed to the next request (controller)
    }
}
  1. Register the Middleware

Add it to app/Http/Kernel.php under the $routeMiddleware property:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    // ... other middleware
    'check.age' => \App\Http\Middleware\CheckAge::class,
];
  1. Use the Middleware on a Route

Now you can apply it to any route:

Route::get('/dashboard', function () {
    return "Welcome to the Dashboard!";
})->middleware('check.age');

if a request is made to /dashboard with an age parameter less than 18, the user will be redirected to /home.

4. Common Middleware Uses

  • Protecting Routes
Route::get('/admin', [AdminController::class, 'index'])->middleware(['auth', 'role:admin']);

→ Only users who are logged in and have the admin role can access this.

  • Filtering Requests: For example, checking if a specific API token exists in the request header.

  • Rate Limiting (Anti-Spam): The throttle:60,1 middleware allows a maximum of 60 requests per minute from a single IP.

  • Logging / Monitoring: Middleware can be used to log every incoming request for analytics or debugging.

The Bottom Line

  • Middleware is an intermediary layer between a user's request and the application's controller.

  • Its purpose is to check, filter, or manipulate the request before it's processed further.

  • The workflow is simple: create it → register it → apply it to a route or controller.