Laravel, one of the most popular PHP frameworks, is constantly evolving to meet modern development needs. With Laravel 12, we see notable changes, especially in how middleware is handled. One of the most significant updates includes the replacement of the traditional Kernel.php file with a more simplified approach using bootstrap/app.php. In this guide, we will explore middleware in Laravel 12, understand the architecture, learn to create custom middleware, and see how to register and use it effectively.

This article is perfect for developers who want to stay up to date with Laravel 12’s best practices and internal structural changes.


What Is Middleware in Laravel?

In Laravel, middleware acts as a bridge between a request and a response. It is used to filter HTTP requests entering your application. Think of it as a gatekeeper that can verify user authentication, restrict access, log activity, or sanitize input before the request reaches your controllers.

Some common use-cases for middleware include:

  • Checking if the user is authenticated
  • Verifying CSRF tokens
  • Logging request data
  • Setting locale or language preferences

What’s New in Laravel 12 Middleware System?

In Laravel 12, one of the major structural changes is the removal of App\Http\Kernel.php. Previously, the Kernel class was used to register global and route middleware. However, in Laravel 12, this responsibility has been moved to the bootstrap/app.php file.

This change makes the framework more flexible and streamlined. It’s easier to manage middleware and simplifies the bootstrapping process.


Understanding bootstrap/app.php in Laravel 12

The bootstrap/app.php file is now responsible for bootstrapping your entire application. It binds all the services and configures middleware directly.

Sample bootstrap/app.php with Middleware Configuration:

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

$app->middleware([
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\TrimStrings::class,
]);

$app->routeMiddleware([
    'auth' => \App\Http\Middleware\Authenticate::class,
    'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
]);

return $app;

As seen above, middleware is now configured directly within the $app instance.


How to Create Middleware in Laravel 12

Creating middleware in Laravel 12 is straightforward and very similar to previous versions. Let’s create a custom middleware that ensures a user has a specific role.

Step-by-Step Guide:

1. Create Middleware Using Artisan Command

php artisan make:middleware CheckUserRole

This command will generate the middleware class in App\Http\Middleware\CheckUserRole.php

2. Define Logic Inside Middleware

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckUserRole
{
    public function handle(Request $request, Closure $next, $role)
    {
        if ($request->user() && $request->user()->role !== $role) {
            return response('Unauthorized', 403);
        }
        return $next($request);
    }
}

This middleware checks if the user has the specified role before proceeding.

3. Register the Middleware in bootstrap/app.php

$app->routeMiddleware([
    'role' => \App\Http\Middleware\CheckUserRole::class,
]);

4. Use Middleware in Routes

Route::get('/admin', function () {
    return 'Admin Panel';
})->middleware('role:admin');

Global vs Route Middleware

Laravel allows you to register middleware globally or per route.

  • Global middleware runs for every request.
  • Route middleware only runs for specific routes.

This distinction helps optimize performance and keeps logic modular.

🔗 Internal Link:

Explore more about Route Middleware in Laravel.


Middleware Parameters

As shown above, Laravel middleware can accept parameters. These are passed as arguments when you assign middleware to a route.

For instance:

Route::get('/dashboard', function () {
    return 'Dashboard';
})->middleware('role:user');

The role:user passes “user” as a parameter to the handle() method.


Middleware Groups

Middleware groups let you group several middleware under a single key. This is useful for routes that share a common set of middleware.

Example:

$app->middlewareGroup('web', [
    \App\Http\Middleware\EncryptCookies::class,
    \App\Http\Middleware\StartSession::class,
]);

Now, you can use ->middleware('web') on your routes.


Disabling Middleware in Testing

During unit testing, it’s often helpful to disable middleware to isolate functionality.

$this->withoutMiddleware();

You can also disable specific middleware:

$this->withoutMiddleware([
    \App\Http\Middleware\CheckUserRole::class,
]);

Best Practices for Middleware

  1. Keep Logic Simple: Middleware should only contain logic related to filtering requests.
  2. Use Groups Wisely: Group middleware to simplify route definitions.
  3. Use Parameters for Flexibility: Middleware parameters reduce the need for multiple similar classes.
  4. Name Clearly: Middleware names should reflect their purpose.

Summary: Why This Change Matters

Laravel 12’s shift from Kernel.php to configuring middleware in bootstrap/app.php offers greater control and cleaner application structure. It also aligns better with Laravel’s minimalist philosophy. Developers can now define and register middleware in one place, making it easier to maintain and manage.

Additionally, the syntax is straightforward, and the flexibility to define both global and route middleware remains intact.


Final Thoughts

Middleware is a powerful tool in Laravel. With the changes introduced in Laravel 12, the framework has taken a step forward toward more flexibility and simplicity. By understanding how middleware works and how to implement it efficiently, you can greatly enhance the security, performance, and user experience of your Laravel applications.

So, whether you’re filtering requests, handling permissions, or logging data—middleware is your best friend.


💡 Explore Further


Feel free to reach out if you need help implementing middleware or upgrading your Laravel app! Let’s build something scalable and powerful together. 🚀

Dalpat Singh Rathore – Laravel Developer | Web & App Expert

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top