LARAVEL Tutorial


Laravel 6 Middleware Tutorial


The Laravel Middleware is filtering mechanism for web applications, which is used to filters HTTP requests and return the response. In other words, Middleware works as a bridge between a client request and a server response.

Suppose an unauthorized user requests in your web application. And you can filter the request of that unauthorized user. For this, you will have to use the Laravel Middleware mechanism for filter unauthorized user requests.

In this tutorial, You will learn how to create, register, and use of laravel middleware.

Create Middleware

Creating middleware in Laravel is very easy and simple. First of all open your command prompt and then go to the root directory of your Laravel application and type the below following given command on cmd (command prompt).

// You can name your middleware by replacing CheckAge.

php artisan make:middleware CheckAge  

The above make:artisan command will place a new CheckAge middleware within your app/Http/Middleware directory. In CheckAge middleware, we will only allow access to the route if the provided age is greater than 50. Otherwise, we will redirect the user's back to the home URI.

Go to app/Http/Middleware/CheckAge.php and write your own logic here:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->age <= 50) {
            return redirect('/');
        }

        return $next($request);
    }

}

Registering a Middleware

Laravel provides two types for register Middlewares. These are:

  • Global Middleware
  • Route Middleware

Global Middleware

Global middlewares are filter every HTTP request of your web application. In the $middleware property of your app/Http/Kernel.php class, you can register your middleware as global of your web application, you could do like:

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckAge::class, // register here
];

Route Middleware

Route middlewares are filter specific routes HTTP request of your web application. In the $routeMiddleware  property of your app/Http/Kernel.php class, you can register your middleware as route middleware of your web application, you could do like:

protected $routeMiddleware = [
   'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'checkAge' => \Illuminate\Routing\Middleware\CheckAge::class,
];

Use middleware to Specific routes

You can use middleware on single or multiple routes also, you could do like this:

Route::get('hello/{param}', ['middleware' => 'checkAge', function () {
    return "singel Route";
}]);

Use Multiple Middleware to Specific routes

You can use multiple middlewares on single or multiple routes also, you could do like this:

Another to add middleware to routes is to call a middleware method on the route definition. Like this.

Route::get('hello/{param}', function () {
    //
})->middleware(['first_middleware', 'second_middleware']);

Middleware Parameters

If you want to pass parameters in middleware, it is very easy and simple. Laravel middleware allows passing parameters in middleware class. You could do like below:

public function handle($request, Closure $next, $role)
{
    if (! $request->user()->hasRole($role)) {
        // Redirect...
    }

    return $next($request);
}

Now attach middleware

Route::post('hello/{id}', ['middleware' => 'role:editor', function ($id) {
    //
}]);

In the above example, Laravel middleware validates the user's role. Before allowing access to any HTTP request on your web application.