How To Create Custom Middleware In Laravel

In this tutorial I will give you example about how to create custom middleware in laravel 6, laravel 7 and laravel 8. laravel 7/8 custom middleware 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. If in your project's have multiple user then we need to use middleware to provide diffrent access or login to diffrent users.

So, let's start create custom middleware in laravel 7/8.

In this example, I have created "roleType" middleware and I will use simply on route, when they route will run you must have to pass "type" parameter and then you can access those request like as below demo link:




Step 1 : Create Custom Middleware

First we need to create custome middleware. So, run below command in your terminal and create middleware. 

php artisan make:middleware RoleType

After run above command you will find one file on app/Http/Middleware/RoleType.php location and you have to add below code:


namespace App\Http\Middleware;

use Closure;

class RoleType
    public function handle($request, Closure $next)
        if ($request->type != 'admin') {
            return response()->json('Please enter valid role type');

        return $next($request);


Step 2 : Register This Middleware on Kernel File

After creating middleware. we have to register this middleware on kernel file.


 protected $routeMiddleware = [
        'roleType' => \App\Http\Middleware\RoleType::class,



 Step 3 : Add Route

Now add route and add RoleType middleware on specific route like below code. 



Step 4 :  Add Controller

Add below code in UserController with checkrole function.


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
    public function checkRole()

Now, it's time to run so, copy below link and get output.



You might also like :


Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.