How to Create Middleware with Parameters in Laravel?

By Hardik Savani | June 8, 2016 | Category : Laravel

Laravel is the best framework in PHP todays. Laravel framework provide saveral functionality and you can also find from this site. But now in this post you can learn how to create custom middleware with passing parameters in laravel 5 example and how to use middleware with route parameters in laravel 5. In this example you can learn how to add middlware with check user have access role for this route from scratch in your laravel application.

I also added how to create middleware in my previous post, you can see that also.

In this example i added middleware for check use have role access for this route. So i added < So first create RoleMiddleware middleware using bellow command:

Create Middleware

php artisan make:middleware RoleMiddleware

Ok, now you can found RoleMiddleware.php in app/Http/Middleware directory and open RoleMiddleware.php file and put bellow code on that file. In this file i check given parameter role is access for current login user or not.


namespace App\Http\Middleware;

use Closure;

use Auth;

class RoleMiddleware



* Handle an incoming request.


* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed


public function handle($request, Closure $next, $role)


if (! $request->user()->hasRole($role)) {

return redirect()->route('home');


return $next($request);



Now we need to register and create aliase above middleware in Kernel.php file so first open Kernel.php and add bellow line.


namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel



protected $routeMiddleware = [


'role' => \App\Http\Middleware\RoleMiddleware::class,



Now we are ready to use role middleware in routes.php file. so you can see how to use middleware in routes.php file.


Route::get('home', ['as'=>'home','uses'=>'[email protected]']);

Route::group(['middleware' => 'role:admin'], function () {

Route::get('admins', ['as'=>'admins','uses'=>'[email protected]']);



Route::get('home', ['as'=>'home','uses'=>'[email protected]']);

Route::get('admins', ['as'=>'admins','uses'=>'[email protected]','middleware' => 'role:admin']);

you can pass also multiple parameters as you want....

Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: