Middleware

Introduction

Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.

Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

1php artisan make:middleware EnsureTokenIsValid
1php artisan make:middleware EnsureTokenIsValid

This command will place a new EnsureTokenIsValid class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied token input matches a specified value. Otherwise, we will redirect the users back to the home URI:

1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class EnsureTokenIsValid
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next): Response
17 {
18 if ($request->input('token') !== 'my-secret-token') {
19 return redirect('home');
20 }
21 
22 return $next($request);
23 }
24}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class EnsureTokenIsValid
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next): Response
17 {
18 if ($request->input('token') !== 'my-secret-token') {
19 return redirect('home');
20 }
21 
22 return $next($request);
23 }
24}

As you can see, if the given token does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the $next callback with the $request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

[!NOTE]
All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middleware's constructor.

Middleware and Responses

Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task before the request is handled by the application:

1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class BeforeMiddleware
10{
11 public function handle(Request $request, Closure $next): Response
12 {
13 // Perform action
14 
15 return $next($request);
16 }
17}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class BeforeMiddleware
10{
11 public function handle(Request $request, Closure $next): Response
12 {
13 // Perform action
14 
15 return $next($request);
16 }
17}

However, this middleware would perform its task after the request is handled by the application:

1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class AfterMiddleware
10{
11 public function handle(Request $request, Closure $next): Response
12 {
13 $response = $next($request);
14 
15 // Perform action
16 
17 return $response;
18 }
19}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class AfterMiddleware
10{
11 public function handle(Request $request, Closure $next): Response
12 {
13 $response = $next($request);
14 
15 // Perform action
16 
17 return $response;
18 }
19}

Registering Middleware

Global Middleware

If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.

Assigning Middleware to Routes

If you would like to assign middleware to specific routes, you may invoke the middleware method when defining the route:

1use App\Http\Middleware\Authenticate;
2 
3Route::get('/profile', function () {
4 // ...
5})->middleware(Authenticate::class);
1use App\Http\Middleware\Authenticate;
2 
3Route::get('/profile', function () {
4 // ...
5})->middleware(Authenticate::class);

You may assign multiple middleware to the route by passing an array of middleware names to the middleware method:

1Route::get('/', function () {
2 // ...
3})->middleware([First::class, Second::class]);
1Route::get('/', function () {
2 // ...
3})->middleware([First::class, Second::class]);

For convenience, you may assign aliases to middleware in your application's app/Http/Kernel.php file. By default, the $middlewareAliases property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it an alias of your choosing:

1// Within App\Http\Kernel class...
2 
3protected $middlewareAliases = [
4 'auth' => \App\Http\Middleware\Authenticate::class,
5 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
6 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
7 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
8 'can' => \Illuminate\Auth\Middleware\Authorize::class,
9 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
10 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
11 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
12 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
13];
1// Within App\Http\Kernel class...
2 
3protected $middlewareAliases = [
4 'auth' => \App\Http\Middleware\Authenticate::class,
5 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
6 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
7 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
8 'can' => \Illuminate\Auth\Middleware\Authorize::class,
9 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
10 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
11 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
12 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
13];

Once the middleware alias has been defined in the HTTP kernel, you may use the alias when assigning middleware to routes:

1Route::get('/profile', function () {
2 // ...
3})->middleware('auth');
1Route::get('/profile', function () {
2 // ...
3})->middleware('auth');

Excluding Middleware

When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method:

1use App\Http\Middleware\EnsureTokenIsValid;
2 
3Route::middleware([EnsureTokenIsValid::class])->group(function () {
4 Route::get('/', function () {
5 // ...
6 });
7 
8 Route::get('/profile', function () {
9 // ...
10 })->withoutMiddleware([EnsureTokenIsValid::class]);
11});
1use App\Http\Middleware\EnsureTokenIsValid;
2 
3Route::middleware([EnsureTokenIsValid::class])->group(function () {
4 Route::get('/', function () {
5 // ...
6 });
7 
8 Route::get('/profile', function () {
9 // ...
10 })->withoutMiddleware([EnsureTokenIsValid::class]);
11});

You may also exclude a given set of middleware from an entire group of route definitions:

1use App\Http\Middleware\EnsureTokenIsValid;
2 
3Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
4 Route::get('/profile', function () {
5 // ...
6 });
7});
1use App\Http\Middleware\EnsureTokenIsValid;
2 
3Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
4 Route::get('/profile', function () {
5 // ...
6 });
7});

The withoutMiddleware method can only remove route middleware and does not apply to global middleware.

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the $middlewareGroups property of your HTTP kernel.

Laravel includes predefined web and api middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, these middleware groups are automatically applied by your application's App\Providers\RouteServiceProvider service provider to routes within your corresponding web and api route files:

1/**
2 * The application's route middleware groups.
3 *
4 * @var array
5 */
6protected $middlewareGroups = [
7 'web' => [
8 \App\Http\Middleware\EncryptCookies::class,
9 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
10 \Illuminate\Session\Middleware\StartSession::class,
11 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
12 \App\Http\Middleware\VerifyCsrfToken::class,
13 \Illuminate\Routing\Middleware\SubstituteBindings::class,
14 ],
15 
16 'api' => [
17 \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
18 \Illuminate\Routing\Middleware\SubstituteBindings::class,
19 ],
20];
1/**
2 * The application's route middleware groups.
3 *
4 * @var array
5 */
6protected $middlewareGroups = [
7 'web' => [
8 \App\Http\Middleware\EncryptCookies::class,
9 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
10 \Illuminate\Session\Middleware\StartSession::class,
11 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
12 \App\Http\Middleware\VerifyCsrfToken::class,
13 \Illuminate\Routing\Middleware\SubstituteBindings::class,
14 ],
15 
16 'api' => [
17 \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
18 \Illuminate\Routing\Middleware\SubstituteBindings::class,
19 ],
20];

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups make it more convenient to assign many middleware to a route at once:

1Route::get('/', function () {
2 // ...
3})->middleware('web');
4 
5Route::middleware(['web'])->group(function () {
6 // ...
7});
1Route::get('/', function () {
2 // ...
3})->middleware('web');
4 
5Route::middleware(['web'])->group(function () {
6 // ...
7});

[!NOTE]
Out of the box, the web and api middleware groups are automatically applied to your application's corresponding routes/web.php and routes/api.php files by the App\Providers\RouteServiceProvider.

Sorting Middleware

Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In this case, you may specify your middleware priority using the $middlewarePriority property of your app/Http/Kernel.php file. This property may not exist in your HTTP kernel by default. If it does not exist, you may copy its default definition below:

1/**
2 * The priority-sorted list of middleware.
3 *
4 * This forces non-global middleware to always be in the given order.
5 *
6 * @var string[]
7 */
8protected $middlewarePriority = [
9 \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
10 \Illuminate\Cookie\Middleware\EncryptCookies::class,
11 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
12 \Illuminate\Session\Middleware\StartSession::class,
13 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
14 \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
15 \Illuminate\Routing\Middleware\ThrottleRequests::class,
16 \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
17 \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class,
18 \Illuminate\Routing\Middleware\SubstituteBindings::class,
19 \Illuminate\Auth\Middleware\Authorize::class,
20];
1/**
2 * The priority-sorted list of middleware.
3 *
4 * This forces non-global middleware to always be in the given order.
5 *
6 * @var string[]
7 */
8protected $middlewarePriority = [
9 \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
10 \Illuminate\Cookie\Middleware\EncryptCookies::class,
11 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
12 \Illuminate\Session\Middleware\StartSession::class,
13 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
14 \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
15 \Illuminate\Routing\Middleware\ThrottleRequests::class,
16 \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
17 \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class,
18 \Illuminate\Routing\Middleware\SubstituteBindings::class,
19 \Illuminate\Auth\Middleware\Authorize::class,
20];

Middleware Parameters

Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create an EnsureUserHasRole middleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the $next argument:

1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class EnsureUserHasRole
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next, string $role): Response
17 {
18 if (! $request->user()->hasRole($role)) {
19 // Redirect...
20 }
21 
22 return $next($request);
23 }
24 
25}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class EnsureUserHasRole
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next, string $role): Response
17 {
18 if (! $request->user()->hasRole($role)) {
19 // Redirect...
20 }
21 
22 return $next($request);
23 }
24 
25}

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a ::

1Route::put('/post/{id}', function (string $id) {
2 // ...
3})->middleware('role:editor');
1Route::put('/post/{id}', function (string $id) {
2 // ...
3})->middleware('role:editor');

Multiple parameters may be delimited by commas:

1Route::put('/post/{id}', function (string $id) {
2 // ...
3})->middleware('role:editor,publisher');
1Route::put('/post/{id}', function (string $id) {
2 // ...
3})->middleware('role:editor,publisher');

Terminable Middleware

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware and your web server is using FastCGI, the terminate method will automatically be called after the response is sent to the browser:

1<?php
2 
3namespace Illuminate\Session\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class TerminatingMiddleware
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next): Response
17 {
18 return $next($request);
19 }
20 
21 /**
22 * Handle tasks after the response has been sent to the browser.
23 */
24 public function terminate(Request $request, Response $response): void
25 {
26 // ...
27 }
28}
1<?php
2 
3namespace Illuminate\Session\Middleware;
4 
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8 
9class TerminatingMiddleware
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
15 */
16 public function handle(Request $request, Closure $next): Response
17 {
18 return $next($request);
19 }
20 
21 /**
22 * Handle tasks after the response has been sent to the browser.
23 */
24 public function terminate(Request $request, Response $response): void
25 {
26 // ...
27 }
28}

The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of routes or global middleware in the app/Http/Kernel.php file.

When calling the terminate method on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handle and terminate methods are called, register the middleware with the container using the container's singleton method. Typically this should be done in the register method of your AppServiceProvider:

1use App\Http\Middleware\TerminatingMiddleware;
2 
3/**
4 * Register any application services.
5 */
6public function register(): void
7{
8 $this->app->singleton(TerminatingMiddleware::class);
9}
1use App\Http\Middleware\TerminatingMiddleware;
2 
3/**
4 * Register any application services.
5 */
6public function register(): void
7{
8 $this->app->singleton(TerminatingMiddleware::class);
9}

Comments

No Comments Yet

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.