0
0
Laravelframework~5 mins

Why middleware filters requests in Laravel

Choose your learning style9 modes available
Introduction

Middleware acts like a gatekeeper that checks requests before they reach your app. It helps keep your app safe and organized by filtering requests.

To check if a user is logged in before showing a page.
To block bad or harmful requests from reaching your app.
To add extra information to requests, like language or location.
To log or track requests for monitoring.
To redirect users based on certain rules, like age or role.
Syntax
Laravel
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckSomething
{
    public function handle(Request $request, Closure $next)
    {
        // Check or modify the request here
        if (/* some condition */) {
            return redirect('somewhere');
        }

        return $next($request);
    }
}
Middleware classes have a handle method that gets the request and a next function.
You must call $next($request) to let the request continue to the app.
Examples
This example checks if the user is logged in. If not, it sends them to the login page.
Laravel
<?php
public function handle(Request $request, Closure $next)
{
    if (!$request->user()) {
        return redirect('login');
    }
    return $next($request);
}
This example blocks requests that have a specific header, stopping them with a 403 error.
Laravel
<?php
public function handle(Request $request, Closure $next)
{
    if ($request->header('X-Blocked')) {
        abort(403, 'Access denied');
    }
    return $next($request);
}
Sample Program

This middleware checks if the user is under 18 years old. If yes, it redirects them to a 'no-access' page. Otherwise, it lets the request continue.

Laravel
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->input('age') < 18) {
            return redirect('no-access');
        }
        return $next($request);
    }
}
OutputSuccess
Important Notes

Always call $next($request) to pass the request along.

Middleware can stop requests early by returning a response like redirect or error.

Summary

Middleware filters requests to protect and control access.

It checks or changes requests before they reach your app.

You use middleware to keep your app safe and organized.