How To Create Custom Middleware In Laravel

WebSolutionStuff | Aug-24-2020 | Categories : Laravel

In this tutorial i will give you information about middleware and i will show you how to create custom  middleware in laravel.

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 and follow my step and create your own custom middleware

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 Middleware

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

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
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if ($request->type != 'admin') {
            return response()->json('Please enter valid type');

        return $next($request);


Step 2 : Register This Middleware on Kernel File

After successfully add this code of 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 in this route 

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


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 this example copy below link in your url and get output.



Recommended Post
Featured Post

Follow us
facebooklogo github instagram twitter