What is middleware in Laravel and how to use it

Middleware is something like when you visit a mall, at the entrance, a security guard does the checking then he permits you to enter into the mall. So the security guard is here middleware. Similarly in Laravel when you make an HTTP request it goes through a middleware before it accesses the intended block of code. Let’s see what is middleware in Laravel and how to use it.

So now your question would be “do all HTTP request in laravel goes through middleware“. The answer is NO, in Laravel you can setup which HTTP request should go through middleware.

Let’s think of a scenario where we can set up middleware, Suppose you have a blog website with the domain name “myblog.com”. Now the website is accessible to all readers. You always create a new post by visiting “myblog.com/admin/newpost” but this URL can also be accessed by any users. So to prevent any users to access this URL you can set up middleware to check that the user is authorized or not to proceed with that URL.

How to use middleware in Laravel

I am assuming you have the setup of laravel project, if not then follow this article to set up a laravel project. To see a use-case of middleware we will apply middleware on a few routes.

To create a middleware a new open terminal or cmd in the laravel project directory and type the following command.

php artisan make:middleware Is

This command will create a middleware file in “app/Htpp/Middleware” with the name IsAdmin.php. So in this file, we will put the condition if the user is admin then he can proceed otherwise redirect to home. everytime you create a new middleware you have to register that middleware. To register middleware open file “app/Http/kernel.php” and you will see variable $routeMiddleware. Add your newly created middleware in this variable like this.

   protected $routeMiddleware = [
      ....
        'isadmin' => \App\Http\Middleware\IsAdmin::class,
    ];

Next, Lets assume in “routes/web.php” have following routes .

...
Route::group(['middleware' => 'isadmin'], function () {
    Route::get('/role', function () {
        return "<h1>hello, Admin</h1>";
    });
});
Route::get('/home', function () {
    return "<h1>You are not admin</h1>";
});
Route::get('/', function () {
    return view("welcome");
});
...

In the first line, we can see the route with the middleware name we just created. So in the callback function of Route::group we have created another Route with the role. So route with the role will only be accessed when it will pass the middleware. We have other routes as well which is not in the middleware group so they can be accessed by anyone.

Its time to write the condtion in middelware earlier we created .Open IsAdmin.php and replace handle function with the following condition.

    public function handle($request, Closure $next)
    {
        if($request['name']!=='admin'){
        return redirect('/home');
        }
        return $next($request);
    }

In above code we are checking if name is not equal to admin then redirect back to the home route.And if it is true proceed further.

We have done the coding part, now lets verify and check output. To verify that start the server by running following command

php artisan serve

Now your server is started on localhost or 127.0.0.1:8000. Open your browser and paste the URL “127.0.0.1:8000“.

To test our scenario enter first wrong name (other than admin) the following URL.

http://127.0.0.1:8000/role?name=user

This will redirect back to the home route.

middleware in Laravel

Lets pass right name in URL parameter and see the result.

http://127.0.0.1:8000/role?name=admin
middleware in Laravel

This is how middleware work. In real project you might not use middleware with this kind of condition. In real project to verify user and admin we use database . May be in next article I will do with database. It was just simply working scenario of middleware .

I hope this article has helped you to understand working of middleware in laravel. In case of any query drop the comment in comment box.

That was all about what is middleware in laravel and how to use it.

See also

Leave a Reply

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