In this tutorial you will learn about the Laravel Middleware and its application with practical example.
What is Middleware?
In Laravel, Middleware is a filtering mechanism that facilitates filtering of incoming HTTP request before it is routed to particular controller for further processing. Laravel framework includes several in-built middleware, including authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory. In addition to the built-in middleware, custom middleware can also be created.
Creating Middleware
Middleware can be created by executing the following artisan command –
Syntex:-
1 |
php artisan make:middleware <middleware-name> |
Replace <middleware-name> with name you like for middleware you creating.
For example, we create a middleware that that only allow to admin user to access into admin panel.
Step 1 – So first we create IsAdminMiddleware middleware using following command –
1 |
php artisan make:middleware IsAdminMiddleware |
Step 2 – After successful execution of the above command, IsAdminMiddleware.php will be created at app/Http/Middleware. The newly created IsAdminMiddleware.php will have the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace AppHttpMiddleware; use Closure; class IsAdminMiddleware { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request); } } |
Step 3 – Ok, now open IsAdminMiddleware.php file and put bellow code on that file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
namespace App\Http\Middleware; use Closure; use Auth; class IsAdminMiddleware { public function handle($request, Closure $next) { if(!Auth::check() || Auth::user()->is_admin != '1'){ return redirect()->route('home'); } return $next($request); } } |
Registering Middleware
Once our middleware is created, we have to register it before we use it. The middleware is registered at app/Http/Kernel.php. There are two ways we can register a middleware in Kernel.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ // .. ]; protected $routeMiddleware = [ // ... ]; } |
Global Middleware
If you want your middleware to be run on every HTTP request handled by your application, you need to list your middleware class at the end of $middleware array of your app/Http/Kernel.php class.
1 2 3 4 5 6 7 8 |
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; |
Route Middleware
If you want your middleware to be run on some specific routes, you need to list your middleware in the $routeMiddleware array of your app/Http/Kernel.php class.
1 2 3 4 5 |
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, ]; |
Example:-
We have created IsAdminMiddleware in the above example. Now we can register it in route specific middleware property and create alias for it in Kernel.php file.
Our app/Http/Kernel.php file looks as following –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'is-admin' => \App\Http\Middleware\IsAdminMiddleware::class, ]; } |
Once middleware has been created and registered, you can assign it to any route using middleware key in following ways –
1 2 3 |
Middleware Parameters
Sometime you may want to pass parameters to a Middleware, this can be achieved by passing our custom argument after the $next argument.
The standard middleware funcation looks like as following-
1 2 3 |
public function handle($request, Closure $next) { return $next($request); } |
Imagine, if our application has different type of user roles like author, editor, publisher and admin, and now you want to authenticate the request based on user role, this can be achieved by passing user role as parameter to middleware.
In this case our middleware function will look like as following –
1 2 3 4 |
public function handle($request, Closure $next, $role) { echo "Role: ".$role; return $next($request); } |
We can specify middleware parameters when defining the route by separating the middleware name and parameters with a : and multiple parameters should be delimited by commas(,).
Add the following line of code in app/Http/routes.php file.
1 2 3 4 |
Before & After Middleware
Whether a middleware runs before or after a request depends on the middleware itself.
For example, let’s define a middleware that runs before a request –
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App\Http\Middleware; use Closure; class BeforeMiddleware { public function handle($request, Closure $next) { // Perform action return $next($request); } } |
Now, let’s define a middleware that perform its task after the request –
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace App\Http\Middleware; use Closure; class AfterMiddleware { public function handle($request, Closure $next) { $response = $next($request); // Perform action return $response; } } |
Terminable Middleware
Terminable middleware allows you to perform some task even after the HTTP response is already been sent to the browser.This can be done by defining a middleware as “terminable” middleware. A middleware can be defined as “terminable” by adding a terminate method to it.The terminate method accepts two arguments $request and $response. Once a terminable middleware is created it should be registered as global middleware in app/Http/Kernel.php file.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Http\Middleware; use Closure; class TerminableMiddleware { public function handle($request, Closure $next) { return $next($request); } public function terminate($request, $response){ // Statements to be executed after response } } |