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;
6 
7class EnsureTokenIsValid
8{
9 /**
10 * Handle an incoming request.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @param \Closure $next
14 * @return mixed
15 */
16 public function handle($request, Closure $next)
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;
6 
7class EnsureTokenIsValid
8{
9 /**
10 * Handle an incoming request.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @param \Closure $next
14 * @return mixed
15 */
16 public function handle($request, Closure $next)
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.

lightbulb

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

Middleware & 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;
6 
7class BeforeMiddleware
8{
9 public function handle($request, Closure $next)
10 {
11 // Perform action
12 
13 return $next($request);
14 }
15}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6 
7class BeforeMiddleware
8{
9 public function handle($request, Closure $next)
10 {
11 // Perform action
12 
13 return $next($request);
14 }
15}

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;
6 
7class AfterMiddleware
8{
9 public function handle($request, Closure $next)
10 {
11 $response = $next($request);
12 
13 // Perform action
14 
15 return $response;
16 }
17}
1<?php
2 
3namespace App\Http\Middleware;
4 
5use Closure;
6 
7class AfterMiddleware
8{
9 public function handle($request, Closure $next)
10 {
11 $response = $next($request);
12 
13 // Perform action
14 
15 return $response;
16 }
17}

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 should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choosing:

1// Within App\Http\Kernel class...
2 
3protected $routeMiddleware = [
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 $routeMiddleware = [
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 has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:

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

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', 'second']);
1Route::get('/', function () {
2 //
3})->middleware(['first', 'second']);

When assigning middleware, you may also pass the fully qualified class name:

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

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.

Out of the box, Laravel comes with 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\Session\Middleware\AuthenticateSession::class,
12 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
13 \App\Http\Middleware\VerifyCsrfToken::class,
14 \Illuminate\Routing\Middleware\SubstituteBindings::class,
15 ],
16 
17 'api' => [
18 'throttle:api',
19 \Illuminate\Routing\Middleware\SubstituteBindings::class,
20 ],
21];
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\Session\Middleware\AuthenticateSession::class,
12 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
13 \App\Http\Middleware\VerifyCsrfToken::class,
14 \Illuminate\Routing\Middleware\SubstituteBindings::class,
15 ],
16 
17 'api' => [
18 'throttle:api',
19 \Illuminate\Routing\Middleware\SubstituteBindings::class,
20 ],
21];

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});
lightbulb

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\Cookie\Middleware\EncryptCookies::class,
10 \Illuminate\Session\Middleware\StartSession::class,
11 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
12 \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
13 \Illuminate\Routing\Middleware\ThrottleRequests::class,
14 \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
15 \Illuminate\Session\Middleware\AuthenticateSession::class,
16 \Illuminate\Routing\Middleware\SubstituteBindings::class,
17 \Illuminate\Auth\Middleware\Authorize::class,
18];
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\Cookie\Middleware\EncryptCookies::class,
10 \Illuminate\Session\Middleware\StartSession::class,
11 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
12 \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
13 \Illuminate\Routing\Middleware\ThrottleRequests::class,
14 \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
15 \Illuminate\Session\Middleware\AuthenticateSession::class,
16 \Illuminate\Routing\Middleware\SubstituteBindings::class,
17 \Illuminate\Auth\Middleware\Authorize::class,
18];

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

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

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

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

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

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.