Laravel Middleware

Middleware is a mediator between the request sent by the user and the response. When a user requests something to the server then the request has to pass through the middleware first and the middleware verifies that the request is coming from an authenticated user. If the request is authenticated it will be sent to the server else the middleware will redirect the user to the login page.

Laravel provides several middleware that are used for different purposes e.g Authentication, CSRF Token etc. All the middleware are stored in the app/Http/Middleware folder.

Middleware is like a filter through which each request is filtered and we can check various conditions on each coming request.

Creating Middleware in Laravel

To create a new middleware type following command.

php artisan make:middleware 'CheckSalary'

Here we can see the middleware created successfully. We can find CheckSalary middleware in D:\laraveltestproject\laravel\app\Http\Middleware. (Check in your project path).


Applying Middleware in Laravel


Applying Middleware to all the routes.

We can apply middleware to all the routes or to specific routes. To apply middleware to all the routes follow below steps.

-> we need to add middleware path in the kernel.php to apply it to all the urls.

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\Checksalary::class, //Added salary Middleware
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class
    ];
}

-> Open Checksalary.php middleware file and echo sample text in the handle() function. see below code.

  <?php

  namespace App\Http\Middleware;

  use Closure;
  use Illuminate\Http\Request;

  class Checksalary
  {
      /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Closure  $next
       * @return mixed
       */
      public function handle(Request $request, Closure $next)
      {
          echo "This is check salary middleware";
      
          return $next($request);
      }
  }

  ?>

-> Now enter the project URL.


Applying Middleware to specific routes.

To apply middleware to specific route follow below steps-

-> Open karnel.php and add the salary middleware in the  protected $routeMiddleware = [  ] array.

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'salary' => \Illuminate\Auth\Middleware\Checksalary::class // Added salary middleware
    ];

->Add the middleware code in the web.php file.

Route::get('/profile',function(){

    return '</br> User profile page';
})->middleware('salary');

Route::get('/userlist',function(){

    return 'This is user list';
});

We have added salary middleware to the ‘/profile’ route. Now enter url http://127.0.0.1:8000/profile we can see the text we printed in the middleware.

Now we will check another route where we have not added the middleware. Visit http://127.0.0.1:8000/userlist. Here we can see the text printed in the middleware is not printed for this route. It will only be displayed on ‘/profile’ route.


Checking parameter conditions in the middleware

We can check conditions in the middleware based on the parameters sent in the routes.

Route::get('/{salary}',function(){
      return view('welcome');
  })->middleware('salary');

Now we will add a condition in the middleware to check whether the salary is geater than 50000 or not. Add below code in the Checksalary.php middleware file’s handle() funciton.

    public function handle(Request $request, Closure $next)
    {

         if($request->salary>50000){
             echo "salary is greater than 50000";
         }
         else{
             echo "salary is less than 50000";
         } 

        return $next($request);  
   }

Enter URL http://127.0.0.1:8000/10000

Enter URL http://127.0.0.1:8000/60000

Here we can see that the middleware is checking conditions based on the route parametrs.

Laravel Route Grouping

Grouping routes allows us to group routes together. when we need to apply specific attributes to all the routes we can define them together in a group. when we group routes we do not have to apply attributes to each route individually this avoids code duplication.

we use Route::group method for grouping routes. Route::group( [ ],callback);

lets group routes together.

  

     Route::group([],function(){

      Route::get('/empsalary',function(){
          echo "Empoyeee Salary";
      });

      Route::get('/empprofile',function(){
          echo "Empoyeee Profile";
      });

      Route::get('/empdesignation',function(){
          echo "Empoyeee Designation";
      });
  });



Here we are passing two parameters to group() method. Array and closure function. In the closure function we can pass any number of routes that we want to group. We have defined three routes and grouped them together.

  Route::group([],function(){

      Route::get('/empsalary',function(){
          echo "Empoyeee Salary";
      });

      Route::get('/empprofile',function(){
          echo "Empoyeee Profile";
      });

      Route::get('/empdesignation',function(){
          echo "Empoyeee Designation";
      });
  });



We have configured following routes and grouped them together.

http://127.0.0.1:8000/empsalary
http://127.0.0.1:8000/empprofile
http://127.0.0.1:8000/empdesignation

Laravel Route Path Prefixes

When we want to implement a comon URK structure for routes we can use path prefixes. we can specify the prefix for all the routes grouped together by using prefix array option in the route group. Add below code in web.php file.

  Route::group(['prefix'=>'Employee'],function(){

      Route::get('/empsalary',function(){
          echo "Empoyeee Salary";
      });

      Route::get('/empprofile',function(){
          echo "Empoyeee Profile";
      });

      Route::get('/empdesignation',function(){
          echo "Empoyeee Designation";
      });
  });

We have common structure for below urls try executing you can see that we have added Employee prefix in all the routes defined in the group.

http://127.0.0.1:8000/Employee/empsalary
http://127.0.0.1:8000/Employee/empprofile
http://127.0.0.1:8000/Employee/empdesignation

Using Laravel middleware in group

We can assign middleware to all the routes defined in a group. First we need to create middleware and add it to the kernel.php file. Once we add the middleware we can use them in the group.

We will use salary middleware which we have already created above.

  Route::middleware(['salary'])->group(function(){

      Route::get('/empsalary',function(){
          echo "Empoyeee Salary";
      });

      Route::get('/empprofile',function(){
          echo "Empoyeee Profile";
      });

      Route::get('/empdesignation',function(){
          echo "Empoyeee Designation";
      });
  });

Now we have assigned ‘salary’ middleware to all the above routes. we will see the sample text printed in the salary middleware on these urls.

Prefix on route Names

We can have prefix for each route. Using name() method we can add a specific string as prefix for each route. We need to specify the string with trailing character in the name method.

  Route::name('manager.')->group(function(){

      Route::get('developers',function(){
          return "manager.developers";
      })->name('developers');

  });

We can access above route manager.developers.

In this way we have gone through each topic of Middleware in laravel. Middleware is one of the mejor features of laravel framework which provides a filter between request and the user. Middleware are very usefull when application includes sensetive operations.

About the Author: allcodebuzz

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *