Menü schliessen
Created: July 18th 2025
Last updated: July 14th 2025
Categories: IT Development,  Laravel,  Php
Author: Ian Walser

Laravel Middleware - What It Is, How It Works & How to Use It (Laravel 12)

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Introduction

So you're diving into Laravel and keep hearing the word middleware thrown around? Maybe you've even seen it in route definitions, but you're not entirely sure what it does. Don't worry — in this guide, we’ll break down middleware in Laravel 12 in simple terms, complete with code examples and a real-world use case to get you confident using it in your projects.

What is Middleware in Laravel?

In Laravel, middleware acts like a filter or a gatekeeper. It processes incoming HTTP requests before they reach your controller and can also handle responses before they’re sent back to the browser.

You can use middleware to:

  • Check if the user is authenticated
  • Redirect users based on roles
  • Log request data
  • Modify headers or content
  • Limit access to certain routes

Think of it like this:

If your Laravel app were a club, middleware would be the security guard at the entrance checking IDs, dress codes, or memberships.

Built-in Middleware in Laravel 12

Laravel ships with several handy middleware classes out of the box:

  • "Authenticate" – Ensures the user is logged in.
  • "VerifyCsrfToken" – Protects your app against CSRF attacks.
  • "RedirectIfAuthenticated" – Redirects logged-in users from pages like login/register.
  • "EncryptCookies" – Encrypts cookies for security.
  • "ThrottleRequests" – Limits request rates to prevent abuse.

These middleware are typically applied globally (to all requests) or to specific routes as needed.

Creating Custom Middleware in Laravel

Let’s walk through creating a simple custom middleware in Laravel 12.

Goal: Block users from accessing a route after 6 PM

Step 1: Generate the Middleware

php artisan make:middleware BlockAfterSix

Step 2: Add Logic in the Middleware

Edit "app/Http/Middleware/BlockAfterSix.php" like so:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BlockAfterSix
{
    public function handle(Request $request, Closure $next): Response
    {
        if (now()->hour >= 18) {
            return response('Sorry, this page is only accessible before 6 PM.', 403);
        }

        return $next($request);
    }
}

Step 3: Register the Middleware

Open "bootstrap/app.php" and locate where your app is bootstrapped:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(...) 
    ->withMiddleware(function (Middleware $middleware): void {
        // Global middleware
        $middleware->append(\App\Http\Middleware\BlockAfterSix::class);
        
        // OR register as route middleware
        $middleware->alias([
            'block.after.six' => \App\Http\Middleware\BlockAfterSix::class,
        ]);
    })
    ->create();

Use "append()" for global middleware or "alias()" to apply it selectively via routes.

Step 4: Apply to a Route

Route::get('/special-offer', function () {
    return view('special-offer');
})->middleware('block.after.six');

Now if someone visits "/special-offer" after 6 PM, they'll get a 403 error.

Middleware Lifecycle: How It Works Internally

Here’s what happens when you apply middleware:

  1. User hits a route like "/dashboard"
  2. Middleware registered for that route runs first
  3. If conditions are met, request continues to controller
  4. If not, it may redirect or return a different response

You can stack multiple middleware. Laravel will run them in the order they appear in the route group or middleware array.

Group Middleware vs Route Middleware

Route Middleware

Apply to individual routes like this:

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');

Middleware Groups

If you're using middleware groups, you can define them in "bootstrap/app.php" like so:

$app->middlewareGroup('web', [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // Other middleware...
]);

This lets you apply multiple middleware to a group of routes:

Route::middleware('web')->group(function () {
    Route::get('/', fn() => view('welcome'));
});

Real-World Use Case: Role-Based Access Middleware

Let’s say you want only admins to access the admin panel.

Step 1: Create Middleware

php artisan make:middleware IsAdmin

Step 2: Add Logic

public function handle(Request $request, Closure $next)
{
    if (auth()->check() && auth()->user()->role === 'admin') {
        return $next($request);
    }

    abort(403, 'Access denied');
}

Step 3: Register via "withMiddleware()"

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'is.admin' => \App\Http\Middleware\IsAdmin::class,
    ]);
});

Step 4: Apply to Routes

Route::middleware('is.admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
});

Tips

  • Always name middleware clearly for future readability
  • Use middleware for logic that applies to many routes (e.g., auth, logging)
  • Keep middleware simple — if logic gets complex, move it to a service class
  • Log middleware responses if debugging unexpected behavior

Additional Learning Resources

Final Thoughts

Middleware is one of Laravel’s most powerful features for maintaining clean, reusable, and secure code. Whether you're building an e-commerce platform, a portfolio site, or a full-blown SaaS app, understanding middleware will save you a ton of time and keep your codebase sane.

Now that you’ve got the hang of the basics, try creating your own middleware for other use cases — like language localization, geo-blocking, or logging traffic. It’s all about building good habits early as you grow your Laravel skills.