Laravel 11 Define Custom Middleware Example

Hardik Savani
3 min readMar 11, 2024

--

Hello, In this post, I will teach you how to create custom middleware in Laravel 11 framework.

The release of Laravel 11 is around the corner and it is packed with a lot of new features and improvements. Laravel 11 comes with a slimmer application skeleton. Laravel 11 introduces streamlined application structure, per-second rate limiting, health routing, etc.

Laravel middleware is a mechanism that filters HTTP requests entering your application. It sits between the request and the application’s core, allowing you to intercept, modify, or reject requests based on certain conditions. Middleware can be used for tasks like authentication, logging, and request manipulation. It provides a flexible way to handle cross-cutting concerns in your application’s HTTP lifecycle, ensuring clean and modular code organization.

In Laravel 11, the method to register middleware has changed. Before Laravel 11, you could register your middleware in the `Kernel.php` file. But in Laravel 11, you need to define middleware in the `app.php` file. In this example, we’ll create a “LogRequests” middleware to log request URLs. So, let’s see the simple example step by step.

  1. Laravel 11 Define New Middleware

We will use the `alias()` method to define new middleware in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->alias([
'logRequests' => \App\Http\Middleware\LogRequests::class,
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

2. Laravel 11 Remove Default Middleware

We will use the `remove()` method to remove the existing default middleware in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

// Using a string
$middleware->remove(\Illuminate\Http\Middleware\ValidatePostSize::class);

// Or removing multiple default middleware
$middleware->remove([
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

3. Laravel 11 Update Where Users and Guests Are Redirected

We will use the `redirectTo()` method to change where users and guests will redirect in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->redirectTo(
guests: '/admin/login',
users: '/dashboard'
);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

4. Laravel 11 Exclude Cookies from being Encrypted

We will use the `encryptCookies()` method to exclude cookies from being encrypted in the URL in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->encryptCookies(except: [
'test',
'example',
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

5. Laravel 11 Exclude Routes from CSRF Protection

We will use the `validateCsrfTokens()` method to exclude routes from CSRF protection in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->validateCsrfTokens(except: [
'/stripe/*',
'/paypal/callback',
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

6. Laravel 11 Exclude Routes from URL Signature Validation

We will use the `validateSignatures()` method to exclude routes from URL signature validation in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->validateSignatures(except: [
'/api/*',
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

7. Laravel 11 Prevent Converting Empty Strings in Requests

We will use the `convertEmptyStringsToNull()` method to prevent converting empty strings in requests in the “bootstrap/app.php” file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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

$middleware->convertEmptyStringsToNull(except: [
fn ($request) => $request->path() === 'admin/home',
]);

})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

I hope it can help you…

--

--

No responses yet