Laravel 6 Middleware Tutorial With Example

Hello Artisan 

in this tutorial i am going to discuss about laravel middleware. In this laravel middleware tutorial we will see how we can create our custom middleware and how we can use it in our controller. 

You can see default auth middleware in laravel 6. auth middleware will protect your route url, allow only logged in user to access authorize page only. Do you know how it works. Today, i will share with you how to create custom middleware in laravel 6 application. i write step by step tutorial of use of middleware in php laravel 6.

Middleware are the easiest way of verifying HTTP requests before they are passed to the controller. All middleware in Laravel are created in the Middleware folder, located inside the `app/Http/Middleware` folder.

controllers-middleware-laravel-6

Step 1: Creating a Basic Middleware in Laravel 6

So just follow few step to create custom middleware. Let's start.

The process of creating a middleware is very similar in both Laravel 5 and Laravel 6 application.To create our custom middleware, run this below command.

php artisan make:middleware TestMiddleware

After above run command you will find one file on bellow location and you have to write following code: Paste this following code.

app/Http/Middleware/TestMiddleware.php


namespace App\Http\Middleware;

use Closure;

class TestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {   
        $arr = [
            'Bangladesh',
            'America',
            'Canada',
            'Brasil'
        ];
        if(in_array($request->country,$arr)){
            dd("{$request->country} is available in this array");
        }
        return $next($request);
    }
}

After successfully write logic of middleware then we have to create our route to check it.

Step 2: Create Route

So let's simply open routes.php file and add those route.

routes/web.php

Route::get('/test', '[email protected]');

Step 3: Add Controller Method

Now at last we have to add new controller method test() in your Home Controller. So let's add test() method on HomeController.php file.

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Middleware\TestMiddleware;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware(TestMiddleware::class); //Our Middleware
    }

    public function test()
    {
        return "done";
    }
}

Look we registered our middleware inside our controller. Now this middleware logic will work for this route url. So now if you visit this below url, you will see this below image.

127.0.0.1:8000/test?country=Bangladesh

Now you should see this

laravel-middleware-in-controller

Step 4 : Register Middleware 

See above example, we can still use middleware inside our controller to call our custom middleware class inside our HomeController __contruct method. Now we want to call it using a name like "tom or ben ten". For this we have to register our middleware inside Kernel.php file. so open it and paste this following code.

app/Http/Kernel.php

namespace App\Http;


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel
{
    
    protected $routeMiddleware = [
        
        'tom' => \App\Http\Middleware\TestMiddleware::class,
    ];
}

Have a look, now Tom is our Middleware name. now we can use it like below.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Middleware\TestMiddleware;

class HomeController extends Controller
{
   // public function __construct()
   // {
   //     $this->middleware(TestMiddleware::class); 
  //  }
   
    public function __construct()
    {
        $this->middleware('tom'); //Now we can call it like that
    }
   
}

In addition, you can define the middleware directly to the routes too.Just add the route directly!

Route::get('/test', '[email protected]')->middleware('tom');

Read also : Laravel 6 Authorization using Gates

In this tutorial, I offered an overview of controllers and middleware in Laravel 6.If you wish to add a suggestion or have a question, do leave a comment below
want to add anything in it feel free to comment below.Hope it can help you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website