Understanding Laravel 12 Middleware

Author

Kritim Yantra

Mar 05, 2025

Understanding Laravel 12 Middleware

Welcome to this beginner-friendly guide on Laravel 12 middleware! If you're new to Laravel or web development, don’t worry—we’ll walk through everything step-by-step. In this blog post, we’ll explore what middleware is, how it works in Laravel 12, and how to register it in the bootstrap/app.php file (a change from earlier versions where it was done in app/Http/Kernel.php). By the end, you’ll know how to create and use middleware to enhance your Laravel applications. Let’s dive in!

Table of Contents

  1. What is Middleware?
  2. Why Use Middleware in Laravel?
  3. Creating Middleware in Laravel 12
  4. Registering Middleware
  5. Applying Middleware to Routes
  6. Middleware Parameters
  7. Real-World Example: Authentication Middleware
  8. Conclusion

What is Middleware?

Imagine middleware as a series of checkpoints that an HTTP request must pass through before reaching your application—or before the response is sent back to the user. It’s like a filter or gatekeeper that can inspect, modify, or even block requests based on certain conditions.

For example:

  • Authentication Middleware: Checks if a user is logged in. If not, it redirects them to a login page.
  • Logging Middleware: Records details about every request for debugging purposes.
  • CSRF Protection: Ensures requests are safe and legitimate.

In Laravel, middleware is a powerful tool that helps you manage these tasks efficiently, keeping your code organized and reusable.

Why Use Middleware in Laravel?

Middleware is essential because it helps you:

  • Keep Code Clean: Separates tasks like authentication or validation from your main application logic.
  • Reuse Logic: Once created, middleware can be applied to multiple routes or controllers without duplication.
  • Maintain Control: Ensure that every request meets specific criteria before being processed.

Simply put, middleware helps build secure and organized applications without cluttering your routes or controllers.

Creating a Custom Middleware

Let’s start by creating our own middleware. Laravel’s Artisan command makes this easy.

Open your terminal and run:

php artisan make:middleware CheckAdmin

This generates a new file called CheckAdmin.php in the app/Http/Middleware directory. Open it, and you’ll see something like:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAdmin
{
    public function handle(Request $request, Closure $next)
    {
        return $next($request);
    }
}

The handle method is where your middleware logic lives. Let’s modify it to check if a user is an admin:

public function handle(Request $request, Closure $next)
{
    if (!auth()->check() || !auth()->user()->is_admin) {
        abort(403, 'Unauthorized - Admins only!');
    }
    return $next($request);
}

Here’s what this does:

  • auth()->check(): Ensures the user is logged in.
  • auth()->user()->is_admin: Checks if the authenticated user has the is_admin attribute set to true.
  • abort(403, 'Unauthorized - Admins only!'): Stops the request with a 403 Forbidden error if the check fails.
  • $next($request): Passes the request to the next middleware or controller if the user is an admin.

Registering Middleware in Laravel 12

In Laravel 12, middleware registration now occurs in the bootstrap/app.php file instead of app/Http/Kernel.php. This centralizes configuration and streamlines the setup process.

Here’s an example of the basic structure in bootstrap/app.php:

<?php

use Illuminate\Foundation\Application;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php'
    )
    ->withMiddleware(function ($middleware) {
        //
    })
    ->create();

Let’s explore the three ways to register middleware:

1. Global Middleware

Global middleware runs on every HTTP request. To register your CheckAdmin middleware globally (although for admin checks you might typically use route middleware), add it like this:

->withMiddleware(function ($middleware) {
    $middleware->append(\App\Http\Middleware\CheckAdmin::class);
})

Use append to add it to the end of the global middleware stack, or prepend to add it at the beginning.

2. Middleware Groups

Middleware groups bundle multiple middleware together and apply them to specific route types. For example, create an admin group:

->withMiddleware(function ($middleware) {
    $middleware->group('admin', [
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\CheckAdmin::class,
    ]);
})

This defines an admin group that includes session management and your CheckAdmin middleware.

3. Route Middleware (Aliases)

Route middleware lets you apply middleware to specific routes by giving them an alias. Register the alias like this:

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

Now you can use the alias admin in your routes.

Using Middleware in Routes

With your middleware registered, you can apply it in different ways:

Using an Alias

use Illuminate\Support\Facades\Route;

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

The admin alias applies the CheckAdmin middleware to the route. Only logged-in admins can access the dashboard.

Using a Group

Route::middleware('admin')->group(function () {
    Route::get('/admin/dashboard', function () {
        return "Welcome to the Admin Dashboard!";
    });
    Route::get('/admin/settings', function () {
        return "Admin Settings Page";
    });
});

All routes in the group inherit the middleware defined in the admin group.

In a Controller

class ProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    public function show()
    {
        return "Profile page";
    }
}

This applies the admin middleware to all actions in the controller.

Middleware Parameters

To make your middleware more flexible, you can pass parameters. For instance, update your CheckAdmin middleware to accept a minimum age parameter:

public function handle(Request $request, Closure $next, $minAge)
{
    if ($request->age < $minAge) {
        return redirect('home');
    }
    return $next($request);
}

Then, apply it to a route with the parameter:

Route::get('/profile', function () {
    return "Profile page";
})->middleware('check.age:21');

Here, the middleware checks that the user’s age is at least 21.

Real-World Example: Authentication Middleware

Let’s build a practical example: a middleware that ensures a user is logged in before accessing certain pages.

Step 1: Create the Middleware

Run the following Artisan command:

php artisan make:middleware EnsureUserIsAuthenticated

Step 2: Add the Logic

Open app/Http/Middleware/EnsureUserIsAuthenticated.php and update the handle method:

public function handle(Request $request, Closure $next)
{
    if (!auth()->check()) { // Check if user is logged in
        return redirect('login'); // Redirect if not authenticated
    }
    return $next($request);
}

Step 3: Register the Middleware

In bootstrap/app.php, add it to the route middleware aliases:

->withMiddleware(function ($middleware) {
    $middleware->alias([
        'auth.user' => \App\Http\Middleware\EnsureUserIsAuthenticated::class,
    ]);
})

Step 4: Apply the Middleware

Protect a route by applying the middleware:

Route::get('/dashboard', function () {
    return "Welcome to your dashboard!";
})->middleware('auth.user');

Now, only authenticated users can access the dashboard; others will be redirected to the login page.

Conclusion

Middleware in Laravel 12 is a powerful way to manage HTTP requests and responses, and moving its registration to bootstrap/app.php has made configuration cleaner and more intuitive.

In this guide, we covered:

  • What middleware is and why it’s useful.
  • How middleware works in the request lifecycle.
  • How to create and customize middleware in Laravel 12.
  • Registering middleware using the new withMiddleware method in bootstrap/app.php.
  • Applying middleware to routes and controllers.
  • Using parameters to make middleware flexible.
  • A real-world example of authentication middleware.

The best way to master middleware is to practice! Try creating your own middleware—such as one that logs requests or checks user roles—and apply it to your project. For more insights, check out the official Laravel documentation.

Happy coding, and welcome to the world of Laravel middleware!

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts

Laravel 12 Unleashed: Early Insights & What Lies Ahead
Kritim Yantra Kritim Yantra
Feb 24, 2025
Laravel 12 New Features
Web Development
Laravel 12 New Features
Laravel Php
Kritim Yantra Kritim Yantra
Feb 25, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025