7 min read

Laravel middleware acts as a middle layer between users and HTTP requests. Laravel provides the middleware mechanism to filter HTTP requests entering in your application. For example, When the user requests the server, it will pass through the Laravel middleware. If the middleware finds the user authenticated, it will redirect to the requested page otherwise the user has to login first.

Middleware can be used to perform various other tasks, such as CORS middleware adds headers in the responses. You can make your own middleware too. In this tutorial, you will learn about how to create a custom Laravel middleware.

Step 1: Create Custom Middleware

Open your terminal, navigate to your project’s root directory, and run this command: 

php artisan make:middleware CheckUser

This command will create a CheckUser.php file in the app/Http/Middleware/ directory. 

<?php namespace App\Http\Middleware; use Closure;   class CheckUser{   /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next){       if ( condition ){           // Next page        }       return $next($request);    }}

Step 2: Register the Middleware in the Kernel file

Open app/Http/Kernel.php file.

<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel{   ….    /**     * The application’s route middleware.     *     * These middlewares may be assigned to groups or used individually.     *     * @var array     */    protected $routeMiddleware=[        ….        ‘CheckUser’=> \App\Http\Middleware\CheckUser::class,    ];}

Step 3: Add Route

To assign middleware to the route, use the middleware() method:

Route::get(‘admin/profile’, function (){})->middleware(‘CheckUser’);

You can group several middlewares under a single key, to easily assign them to a route.

Route::group([‘middleware’=> [‘CheckUser’]], function (){   //});

Conclusion

Middleware is the Controllers in Model-View-Controller architecture. Here I gave a brief note on Middleware and a short tutorial for how to create custom Middleware in laravel. If you have any queries or suggestions, do leave a comment below and share this on your social media walls. 

If you are looking for a software firm to create your business website or mobile app, your search ends here. We build affordable and robust software solutions for businesses to digitally thrive on. Contact us to get a quote. You can mail us at info@qrolic.com or WhatsApp us on +91 95 37 84 38 39.

"Have WordPress project in mind?

Explore our work and and get in touch to make it happen!"