Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a CheckRole
middleware that receives a role name as an additional argument.
Additional middleware parameters will be passed to the middleware after the $next
argument:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}
return $next($request);
}
}
:
. Multiple parameters should be delimited by commas:
Route::put('post/{id}', function ($id) {
//
})->middleware('role:editor');
Example(1)
php artisan make:middleware RoleMiddleware
2. RoleMiddleware.php in app/Http/Middleware directory and open RoleMiddleware.php file and Implement below code to that file.
In this file checks given parameter userrole is access for current login user or not.
app/Http/Middleware/RoleMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use DB;
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('/');
}
return $next($request);
}
}
3.Now open kernel.php file and register above middleware in Kernel.php file so open Kernel.php and implement code as below
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,
];
}
4.Now cal role middleware in routes.php file.open web.php file and implement code as below
web.php
Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);
Route::get('demo', ['as'=>'admins','uses'=>'demoController@admins','middleware' => 'role:admin']);