> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Middleware

> Learn how to filter and preprocess HTTP requests using Laravel middleware.

## What is middleware

Middleware is a mechanism for inspecting and filtering HTTP requests entering your application.
You can slot in processing before and after the request is handed off to a controller.

For example, Laravel includes authentication middleware.
If the user is not authenticated, it redirects them to the login screen; if they are authenticated, it lets the request continue into the application.

Beyond authentication, you can create middleware for many purposes, such as logging, CSRF protection, and rate limiting. For details on Laravel 13's CSRF protection, see [CSRF protection](/en/csrf).

<Info>
  User-defined middleware is typically placed in the `app/Http/Middleware` directory.
</Info>

```mermaid theme={null}
flowchart TD
    A["HTTP request"] --> B["Global middleware<br>(applied to every request)"]
    B --> C["Route middleware<br>(applied to specific routes)"]
    C --> D["Controller / closure"]
    D --> E["Generate response"]
    E --> F["Route middleware<br>(post-processing)"]
    F --> G["Global middleware<br>(post-processing)"]
    G --> H["HTTP response"]
```

## Built-in middleware

Laravel provides two middleware groups by default: `web` and `api`.
The `web` group is automatically applied to `routes/web.php`, and the `api` group is applied to `routes/api.php`.

| `web` middleware group                    |
| ----------------------------------------- |
| `EncryptCookies`                          |
| `AddQueuedCookiesToResponse`              |
| `StartSession`                            |
| `ShareErrorsFromSession`                  |
| `PreventRequestForgery` (CSRF protection) |
| `SubstituteBindings`                      |

Aliases are also configured for commonly used middleware so you can refer to them by short names.

| Alias      | Middleware                                           |
| ---------- | ---------------------------------------------------- |
| `auth`     | `Illuminate\Auth\Middleware\Authenticate`            |
| `guest`    | `Illuminate\Auth\Middleware\RedirectIfAuthenticated` |
| `verified` | `Illuminate\Auth\Middleware\EnsureEmailIsVerified`   |
| `throttle` | `Illuminate\Routing\Middleware\ThrottleRequests`     |

## Creating middleware

Create a new middleware with the `make:middleware` Artisan command.

```shell theme={null}
php artisan make:middleware EnsureTokenIsValid
```

This generates `app/Http/Middleware/EnsureTokenIsValid.php`.
Write your request-handling logic in the `handle` method.

```php theme={null}
<?php

namespace App\Http\Middleware;

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

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->input('token') !== 'my-secret-token') {
            return redirect('/home');
        }

        return $next($request);
    }
}
```

Calling `$next($request)` passes the request to the next step in the application.
When the condition isn't met, return a redirect or response to stop the request.

### Before and after processing

Middleware can perform work **before** or **after** the request.

```php theme={null}
// Do work before the request
public function handle(Request $request, Closure $next): Response
{
    // Pre-processing here

    return $next($request);
}
```

```php theme={null}
// Do work after the response
public function handle(Request $request, Closure $next): Response
{
    $response = $next($request);

    // Post-processing here

    return $response;
}
```

## Registering middleware

### Global middleware

To run middleware on every request, add it to the global stack via `withMiddleware` in `bootstrap/app.php`.

```php theme={null}
// bootstrap/app.php
use App\Http\Middleware\EnsureTokenIsValid;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->append(EnsureTokenIsValid::class);
    });
```

`append` adds to the end of the stack. Use `prepend` to add to the beginning.

### Assigning middleware to routes

To apply middleware to specific routes, call the `middleware` method on the route definition.

```php theme={null}
use App\Http\Middleware\EnsureTokenIsValid;

Route::get('/profile', function () {
    // ...
})->middleware(EnsureTokenIsValid::class);
```

To apply multiple middleware, pass an array.

```php theme={null}
Route::get('/', function () {
    // ...
})->middleware([First::class, Second::class]);
```

To exclude middleware from a specific route, use `withoutMiddleware`.

```php theme={null}
use App\Http\Middleware\EnsureTokenIsValid;

Route::middleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/', function () {
        // This route has the middleware applied
    });

    Route::get('/profile', function () {
        // This route excludes the middleware
    })->withoutMiddleware([EnsureTokenIsValid::class]);
});
```

### Middleware aliases

You can define short aliases for long class names. Configure them in `bootstrap/app.php`.

```php theme={null}
// bootstrap/app.php
use App\Http\Middleware\EnsureUserIsSubscribed;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'subscribed' => EnsureUserIsSubscribed::class,
        ]);
    });
```

You can then apply the alias to routes.

```php theme={null}
Route::get('/profile', function () {
    // ...
})->middleware('subscribed');
```

## Middleware groups

Grouping multiple middleware under a single key makes it easier to apply them to routes.
Use `appendToGroup` or `prependToGroup` in `bootstrap/app.php`.

```php theme={null}
// bootstrap/app.php
use App\Http\Middleware\First;
use App\Http\Middleware\Second;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->appendToGroup('group-name', [
            First::class,
            Second::class,
        ]);
    });
```

Apply a group to routes just like a regular middleware.

```php theme={null}
Route::get('/', function () {
    // ...
})->middleware('group-name');

Route::middleware(['group-name'])->group(function () {
    // ...
});
```

To add middleware to the existing `web` or `api` group, dedicated methods are available.

```php theme={null}
// bootstrap/app.php
use App\Http\Middleware\EnsureUserIsSubscribed;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [
            EnsureUserIsSubscribed::class,
        ]);
    });
```

## Middleware parameters

Middleware can accept additional parameters.
Add them after the `$next` argument in the `handle` method.

```php theme={null}
<?php

namespace App\Http\Middleware;

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

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string $role): Response
    {
        if (! $request->user()->hasRole($role)) {
            return redirect('/home');
        }

        return $next($request);
    }
}
```

In the route definition, specify the middleware name and parameters separated by `:`.

```php theme={null}
use App\Http\Middleware\EnsureUserHasRole;

Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware(EnsureUserHasRole::class.':editor');
```

Separate multiple parameters with commas.

```php theme={null}
Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware(EnsureUserHasRole::class.':editor,publisher');
```

## Example: an authentication check middleware

A simple example that redirects users who aren't logged in.

```shell theme={null}
php artisan make:middleware RedirectIfNotAuthenticated
```

```php theme={null}
<?php

namespace App\Http\Middleware;

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

class RedirectIfNotAuthenticated
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()) {
            return redirect('/login');
        }

        return $next($request);
    }
}
```

Apply it to a route.

```php theme={null}
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(RedirectIfNotAuthenticated::class);
```

<Tip>
  Laravel has a built-in `auth` middleware for authentication. Before implementing your own, check whether the existing middleware already meets your needs.
</Tip>

## Next steps

<Card title="HTTP requests" icon="globe" href="/en/requests">
  Learn how to receive request data in your controllers.
</Card>


## Related topics

- [Laravel Folio](/en/folio.md)
- [Laravel AI SDK](/en/ai-sdk.md)
- [OAuth 2.0 Authentication - Google Sheets API for Laravel](/en/packages/laravel-google-sheets/oauth.md)
- [Laravel Pennant](/en/pennant.md)
- [Laravel Sentinel — route protection middleware research](/en/blog/sentinel-introduction.md)
