DEV Community

Robin  Dev
Robin Dev

Posted on • Originally published at larachamp.com on

How To Use Middleware In Laravel

We do use middleware in Laravel to make sure authenticated user can access the application. Middleware works like a guard that helps to identify the user. We can create multiple middleware that can be assigned to different routes. We also can use middleware’s as default on each route for that we have to register middleware into app/Http/Kernel.php In $middleware property.

What Is Middleware

Laravel has this Midlleware option that helps us to secure our application or routes. If I would explain it as I have used it, then It helps to authenticate the user and validate the request from user. “validate the request from user” what does it mean? so, For example, if you are trying to login in any laravel application or trying to switch on any URL then middleware checks you have permission to the route or not.

If not then it returns the request back to login page or home page. So, Again it’s kind of body guard that prevents application from unauthorized requests.

How to create Middleware


create middleware

Creating a middleware is not so hard, Just put a line of Artisan Command will help you to make new one.

php artisan make:middleware PostManager
Enter fullscreen mode Exit fullscreen mode

When you will run this command you will have this middleware in your directory in app/Http/Middleware/PostManager.php

use Closure;
use Illuminate\Http\Request;

class PostManager
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

You can write whatever stuff you want to write into this middleware. Let me give you a hint. For example, we are creating a middleware that can check if user who is making the request is Manager or not. Then we gonna do like:

<?php

namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PostManager
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();
        if ($user->usertype == 1) {
            return redirect(RouteServiceProvider::HOME);
        }else{
         return route()->redirect('login');
        }         
        return $next($request);
    }
}

Enter fullscreen mode Exit fullscreen mode

We will check if a user has usertype=1or not, if yes then will return it to dashboard. Otherwise redirect to login page.

Types Of Middleware In Laravel

Laravel includes middleware and there are two types of middleware’s.

  • Global Middleware.
  • Route Middleware

Global Middleware

Before moving anywhere let’s talk about Global Middleware, When you do create any route or make any request then you can assign middleware individually for specific reason. But if you want to have a middleware which can check all the request as a Global middleware. Then you can use Global Middleware.

How to define Global Middleware

Let’s define a middleware for that you have to go into your directory structure like app/Http/Kernel.php in which you will have two properties $middleware, $routeMiddleware. In $middleware you can register your created middleware and It will work on all the requests made by you.

 protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \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,
    ];
Enter fullscreen mode Exit fullscreen mode

Route Middleware

The route middleware is bit different from Global Middleware the difference is route middleware works on specific routes where it has assigned to. And on the other side, Global mIddleware work globally. So, basically Route Middleware uses in routes to check wether a user have permission or not to access that particular URL. let’s see how we can define it.

How to define Route Middleware

It is easy to define a Route Middleware. You have to go to app/Http/Kernel.php and in which you will have $routeMiddleware property. You can add your own created middleware to this property and you can assign key to the added 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,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'postmanager' => \Illuminate\Auth\Middleware\PostManager::class,
];
Enter fullscreen mode Exit fullscreen mode

How to use Middleware In Route File

You can easily use midlleware in Route file that means in routes/web.php. Let’s see how we can use middleware on route.

//for example we have route managerslist and will implement middleware on it.

use App\Http\Middleware\PostManager;

Route::view('/managers','managers')->middleware('postmanager');
Enter fullscreen mode Exit fullscreen mode

If you are working on a big or medium project then you should look at $middlewareGroups then you don’t need to assign middleware individually to each route. Let’s have a look at Group Middleware.

Group Middleware In Laravel

As I have said above, If you are assigning middleware to each route then this is not a clever way to do it. If you have multiple routes on same middleware then you should use Group Middleware which helps you to do this in very convenient way.

How to register Group Middleware

First you have to go to again on your app/Http/Kernel.php then you will have property called $middlewareGroups on which you can register your group middleware.

How to use Group Middleware in Route web.php


Route::middleware(['PostManager'])->group(function () {
    // your stuff
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

These are the main points of Middleware in Laravel. I hope you get them. If you do use middleware to authenticate your application and I think you should use them. I don’t know about anyone else but I do use them with package “Laravel Permission” which is very convenient when it comes to authentication and using Middlewares..

The post How To Use Middleware In Laravel first appeared on larachamp.com.

The post How To Use Middleware In Laravel appeared first on larachamp.com.

Top comments (0)