Laravel Middleware

One of the most important feature in laravel is middleware and it provides the method to filter HTTP requests. It acts as a bridge between a request and a response. In this section, we'll see the middleware's mechanism.

Laravel provides a by default Authenticate middleware i.e alias auth under app\Http\Middleware directory. if we use this middleware, it'll check the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise redirects to the signin page.

Middleware can be created by executing the following artisan command -

php artisan make:middleware middleware_name

We'll create middleware i.e VoteMiddleware using artisan command.

php artisan make:middleware VoteMiddleware

it will be create under app/Http/Middleware directory.

Laravel Middleware

<?php
namespace App\Http\Middleware;
use Closure;
class VoteMiddleware
  {
     public function handle($request, Closure $next)
	   {
	       return $next($request);
	   }
  }

Laravel provides two types of Middlewares.

  • Global Middleware
  • Route Middleware

The Global Middleware are run during every request to your application., where Route Middleware will be declared to a specific route. The middleware registered at app/Http/Kernel.php. $middleware property used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

protected $middleware = [
	\App\Http\Middleware\TrustProxies::class,
	\App\Http\Middleware\CheckForMaintenanceMode::class,
	\App\Http\Middleware\ValidatePostSize::class,
	\App\Http\Middleware\TrimStrings::class,
	\App\Http\Middleware\ConvertEmptyStringsToNull::class,
];
protected $routeMiddleware = [
	  'auth' =>   \App\Http\Middleware\Authenticate::class,
	  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class
	  'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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
  ];

# Example

We've created a VoteMiddleware. now we can now register it in route specific middleware property. Below the code for register the route

Open app/Http/Kernel.php file and paste the below code

protected $routeMiddleware = [
  'auth' =>   \App\Http\Middleware\Authenticate::class,
  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class
  'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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,
  'Vote' => \App\Http\Middleware\VoteMiddleware::class // register middleware
 ];
Route::get('vote/{age}', 'UserController@elligible')->middleware('vote');
Route::get('/not-elligible', 'UserController@not_elligible')->name('not_elligible');

In above, we've created the routes to understand the mechanism of middleware.

public function handle($request, Closure $next)
 { 
        $age = $request->segment(2);
	if ($age >= 18)
	return $next($request);
	 else
	return redirect()->route('not_elligible');
}

Copy the above handle method and replace it with app/Http/Middleware/VoteMiddleware's handle method.

To check middleware, visit your site using a URL similar to this one:

  http://127.0.0.1:8000/vote/18

Laravel Middleware

visit your site using a URL similar to this one:

  http://127.0.0.1:8000/vote/15 i.e second segment i.e 15 should be less than 18

When we navigate to this link, it'll be redirected to not_elligible named route.

Laravel Middleware