Middleware

Middleware filters HTTP requests entering your application.

Syntaxpublic function handle($request, Closure $next) { ... }

Middleware wraps around your request handling — perfect for authentication, logging, or CORS. Each middleware can inspect the request and either pass it along with $next($request) or stop it.

Generate one with php artisan make:middleware EnsureTokenIsValid.

Example

Example · php
namespace App\Http\Middleware;

use Closure;

class EnsureTokenIsValid
{
    public function handle($request, Closure $next)
    {
        if ($request->input('token') !== 'secret') {
            return redirect('/login');
        }
        return $next($request);
    }
}

When to use it

  • An admin panel applies the 'auth' middleware to all routes inside the /admin prefix so unauthenticated requests are redirected to the login page automatically.
  • A multi-tenant application uses a custom middleware to resolve the tenant from the subdomain and bind it in the container before any controller runs.
  • A rate-limiting middleware throttles the public API to 60 requests per minute, returning a 429 response automatically when the limit is exceeded.

More examples

Generate and register a middleware

Artisan generates the middleware file with a handle() stub; you then register it in app/Http/Kernel.php before using it on routes.

Example · bash
php artisan make:middleware EnsureTokenIsValid
# Creates app/Http/Middleware/EnsureTokenIsValid.php

Write a middleware handle method

The handle() method inspects the request and either returns an error response early or calls $next($request) to continue the pipeline.

Example · php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureTokenIsValid
{
    public function handle(Request $request, Closure $next): mixed
    {
        if ($request->input('token') !== config('app.api_token')) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $next($request); // pass to the next layer
    }
}

Apply middleware to route groups

Applies named middleware to individual routes or groups; parameterised middleware like 'role:admin' passes 'admin' as the second argument to handle().

Example · php
// Single route
Route::get('/secret', SecretController::class)
    ->middleware('auth');

// Route group
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/dashboard', DashboardController::class);
    Route::resource('/posts', PostController::class);
});

// Parameterised middleware
Route::get('/admin', AdminController::class)
    ->middleware('role:admin');

Discussion

  • Be the first to comment on this lesson.