How to create middleware with parameters in Laravel 5?

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


Share this post:

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.

app/Http/Middleware/RoleMiddleware.php

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.

app/Http/Kernel.php

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.

app/Http/routes.php

Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);


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

Route::get('admins', ['as'=>'admins','uses'=>'HomeController@admins']);

});

OR

Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);


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

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