What is Laravel Middleware and how to make a custom middleware?

Middleware provides a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

There are several middlewares included in the Laravel framework, including middleware for authentication and CSRF protection. All of this middleware is located in the app/Http/Middlewaredirectory.

Let’s see how to make a custom middleware which checks the user status is active or not if user status 0 then print some message else user redirect to home page.

Step 1: Go to command prompt and type this command php artisan make:middleware  name

Step 2: Register your middleware on app/Http/Kernal.phpusing below code on $routeMiddleware array

'your middleware name' => \App\Http\Middleware\checkStatus::class,

Step 3: I have used Auth functionality so find the user using User Model

use App\User;
public function handle($request, Closure $next)
    {
        $userId = \Auth::id();
        $user = User::find($userId);
        //dd($user);
        if($user->status == 0) {            
            echo "Your account has been disabled";
            exit();
        }
        return $next($request);
    }

Step 4: Next I declared the middleware on __construct() method in HomeController Class because I want to check on whenever the object initialize.

public function __construct()
    {
        $this->middleware('stat');
    }

Do this all steps and make your own middleware easily.

Please follow and like us:

Leave a Reply

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