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:

http://localhost:8000/check/role?type=user
http://localhost:8000/check/role?type=admin

 

 

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:

<?php

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.

app/Http/Kernel.php

 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. 

Route::get('check/role','[email protected]')->middleware('roleType');

 

Step 4 :  Add Controller

Add below code in UserController with checkrole function.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function checkRole()
    {
        dd('checkRole');
    }
}

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

http://localhost:8000/check/role?type=user
http://localhost:8000/check/role?type=admin

 


You might also like :

FEATURE POSTS