Laravel Middleware

Laravel Middleware

Middleware acts as a layer between the user and the request. It means that when the user requests the server then the request will pass through the middleware, and then the middleware verifies whether the request is authenticated or not. If the user's request is authenticated then the request is sent to the backend. If the user request is not authenticated, then the middleware will redirect the user to the login screen.

An additional middleware can be used to perform a variety of tasks except for authentication. For example, CORS middleware is responsible for adding headers to all the responses.

Laravel framework includes several middleware such as authentication and CSRF protection, and all these are located in the app/Http/Middleware directory.

We can say that middleware is an http request filter where you can check the conditions.

In middleware, we are going to discuss the following topics:

  • Make a middleware
  • Apply middleware
  • Check condition in middleware
  • Route middleware

Creating a middleware

Type the command php artisan make:middleware 'name of the middleware'.

Laravel Middleware

In the above screen, we type the command "php artisan make:middleware CheckAge" where CheckAge is the name of the middleware. The above window shows that the middleware has been created successfully with the name "CheckAge".

To see whether the CheckAge middleware is created or not, go to your project. Our project name is laravelproject, so the path for the middleware would be: C:\xampp\htdocs\laravelproject\app\Http\Middleware.

Laravel Middleware

Apply a Middleware

Middleware can be either applied to all the URLs or some particular URLs.

Let's apply the middleware to all the URLs.

Step 1: Open the kernel.php file. If we want to apply the middleware to all the URLs, then add the path of the middleware in the array of middleware.

  1. <?php  
  2. namespace App\Http;  
  3. use Illuminate\Foundation\Http\Kernel as HttpKernel;  
  4. class Kernel extends HttpKernel  
  5. {  
  6.     /** 
  7.      *  The application's global HTTP middleware stack. 
  8.      * 
  9.      * These middleware are run during every request to your  application. 
  10.      * 
  11.      * @var array 
  12.      */  
  13.  protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  
  14. \Illuminate\Foundation\Http \Middleware\ValidatePostSize::class,  
  15.  \App\Http\Middleware\TrimStrings::class,  
  16.  \App\Http\Middleware\CheckAge  
  17. ::class,  
  18.   \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,  
  19.     ];  
  20.   
  21.    /** 
  22.      * The application's route middleware groups. 
  23.      * 
  24.      * @var array 
  25.      */  
  26.       
  27. protected $middlewareGroups = [  
  28.         'web' => [  
  29.             \App\Http\Middleware\EncryptCookies::class,  
  30.             
  31.   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,  
  32.               
  33. \Illuminate\Session\Middleware\StartSession::class,  
  34.               
  35. // \Illuminate\Session\Middleware\AuthenticateSession::class,  
  36.             \Illuminate\View\Middleware   
  37. \ShareErrorsFromSession::class,  
  38.             
  39.   \App\Http\Middleware\VerifyCsrfToken::class,  
  40.               
  41. \Illuminate\Routing\Middleware\SubstituteBindings::class,  
  42.         ],  
  43.   
  44.         'api' => [  
  45.             'throttle:60,1',  
  46.             'bindings',  
  47.         ],  
  48.     ];  
  49.   
  50.       
  51.  /** 
  52.      * The application's route middleware. 
  53.      * 
  54.      * These middleware may be assigned to groups or used individually. 
  55.      * 
  56.      *   
  57. @var array 
  58.      */  
  59.     protected $routeMiddleware = [  
  60.           
  61. 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,  
  62.         'auth.basic' => \Illuminate\Auth\Middleware   
  63. \AuthenticateWithBasicAuth::class,  
  64.           
  65. 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,  
  66.           
  67. 'can' => \Illuminate\Auth\Middleware\Authorize::class,  
  68.         'guest' => \App\Http\Middleware   
  69. \RedirectIfAuthenticated::class,  
  70.       
  71.     'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,  
  72.     ];  
  73. }  

Step 2: Type the command php artisan serve in Git Bash Window.

 

 

Laravel Middleware

Step 3: Open the CheckAge.php file, which you have created as a middleware.

 
 
 
  1. <?php  
  2.   
  3. namespace App\Http\Middleware;  
  4.   
  5. use Closure;  
  6.   
  7. class CheckAge  
  8.   
  9. {  
  10.       
  11. /** 
  12.      * Handle an incoming request. 
  13.      * 
  14.      * @param  \Illuminate\Http  
  15. \Request  $request 
  16.      * @param  \Closure  $next 
  17.      * @return mixed 
  18.      */  
  19.   public function handle($request, Closure $next)  
  20.  {  
  21.  //return "middleware";  
  22. echo "hello world";  
  23. return $next($request);  
  24. }  
  25. }  

Step 4: Now, enter the URL 'http://localhost/laravelproject/public/

 

Laravel Middleware

Let's apply the middleware to some specific routes.

Step 1: Open the kernel.php file. If we want to apply the middleware to some specific routes

  1. <?php  
  2. namespace App\Http;  
  3. use Illuminate\Foundation\Http\Kernel as HttpKernel;  
  4. class Kernel extends HttpKernel  
  5. {  
  6.     /** 
  7.      *  The application's global HTTP middleware stack. 
  8.      * 
  9.      * These middleware are run during every request to your  application. 
  10.      * 
  11.      * @var array 
  12.      */  
  13.   protected $middleware = [  
  14.    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,  
  15.    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,  
  16.   \App\Http\Middleware\TrimStrings::class,  
  17.          
  18.   
  19.     
  20.   
  21. \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,  
  22.     ];  
  23.  /** 
  24.      * The application's route middleware groups. 
  25.      * 
  26.      * @var array 
  27.      */  
  28.  protected $middlewareGroups = [  
  29.  'web' => [  
  30.   \App\Http\Middleware\EncryptCookies::class,  
  31.   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,  
  32.   \Illuminate\Session\Middleware\StartSession::class,  
  33.   // \Illuminate\Session\Middleware\AuthenticateSession::class,  
  34.   \Illuminate\View\Middleware \ShareErrorsFromSession::class,  
  35.  \App\Http\Middleware\VerifyCsrfToken::class,  
  36.  \Illuminate\Routing\Middleware\SubstituteBindings::class,  
  37.  ],  
  38.   
  39.  'api' => [  
  40.             'throttle:60,1',  
  41.             'bindings',  
  42.         ],  
  43.     ];  
  44.  /** 
  45.      * The application's route middleware. 
  46.      * 
  47.      * These middleware may be assigned to groups or used individually. 
  48.      * 
  49.      *   
  50. @var array 
  51.      */  
  52.     protected $routeMiddleware = [  
  53.           
  54. 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,  
  55.         'auth.basic' => \Illuminate\Auth\Middleware   
  56. \AuthenticateWithBasicAuth::class,  
  57.           
  58. 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,  
  59.           
  60. 'can' => \Illuminate\Auth\Middleware\Authorize::class,  
  61.         'guest' => \App\Http\Middleware   
  62. \RedirectIfAuthenticated::class,  
  63.       
  64.     'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,  
  65.    
  66. 'age' =>  \App\Http\Middleware\CheckAge::class ];  
  67.          
  68. }  

In the above code, we have added the code, i.e., ''age' => \App\Http\Middleware\CheckAge::class', where age is the name of the middleware. Now, we can use the 'age' middleware for some specific routes.

 

 

Step 2: Open the CheckAge.php file, which you have created as a middleware.

Step 3: Add the middleware code in the web.php file.

  1. Route::Get('/',function()  
  2. {  
  3.   return view('welcome');  
  4. })-> middleware('age');  
  5. Route::Get('user/profile',function()  
  6. {  
  7.   return "user profile";  
  8. });  

In the above code, we have added middleware in '/' root URL, and we have not added the middleware in the 'user/profile' URL.

 

 

Output:

When we access the root URL, then the output would be:

Laravel Middleware

The above output shows that the middleware code has also been accessed as it is displaying a "hello world".

When we access the URL, i.e., /user/profile, then the output would be:

Laravel Middleware

The above output that the middleware code has not been accessed.

When the parameter is passed in a URL.

web.php

  1. Route::Get('/{age}',function($age)  
  2. {  
  3.   return view('welcome');  
  4. })-> middleware('age');  

CheckAge.php

  1. <?php  
  2. namespace App\Http\Middleware;  
  3. use Closure;  
  4. class CheckAge  
  5. {  
  6.  /** 
  7.  * Handle an incoming request. 
  8.  * 
  9.       
  10. * @param 
  11.   \Illuminate\Http\Request  $request 
  12.  * @param  \Closure  $next 
  13.  * @return mixed 
  14.  */  
  15.   public function handle($request, Closure $next)  
  16.  {  
  17.  //return "middleware";  
  18. echo "this is checkage middleware";  
  19. return $next($request);  
  20. }}  

Output

 

 

Laravel Middleware

Check condition in middleware

Middleware can also be used to check the condition. Let's understand through an example.

 
 
 
  1. Route::Get('/{age}',function($age)  
  2. {  
  3.   return view('welcome');  
  4. })-> middleware('age');  

 

 
 
 
  1. <?php  
  2. namespace App\Http\Middleware;  
  3. use Closure;  
  4. class CheckAge  
  5. {  
  6.       
  7. /** 
  8.      * Handle an incoming request. 
  9.      * 
  10.       
  11. * @param 
  12.   \Illuminate\Http\Request  $request 
  13.      
  14.  * @param  \Closure  $next 
  15.      * @return mixed 
  16.      */  
  17.    
  18.    public function handle($request, Closure $next)  
  19.       
  20. {  
  21.   //return "middleware";  
  22. if($request->age>10)  
  23. {  
  24. echo "Age is greater than 10";  
  25. }  
  26. else  
  27. {  
  28. echo"Age is not greater than 10";  
  29. }  
  30. return $next($request);  
  31.       
  32. }}  

Output:

Laravel Middleware
Laravel Middleware