I got this handle in a middleware called rolMiddleware:
public function handle($request, Closure $next, $roles)
{
//dd($request->user());
foreach ($roles as $rol) {
if ($request->user()->getTipoUsuario($request->user()->tipo_usuario_id)->getNombreTipoUsuario() == $rol) {
return $next($request);
}
}
abort(403, "¡No hay autorizacion!");
}
But $roles is an array, here is the route where I use the middleware:
Route::get('/mid', ['middleware' => 'roles:super admin', function () {
return "done";
}]);
and the error that gives me is:
ErrorException in RolMiddleware.php line 22:
Invalid argument supplied for foreach()
You may thing that I do not need an array because I am only using it in super admin, for that route I only need super admin, but there would be routes that can be for super admin and the admin of an area.
In laravel , you can separate your parameters which you want to pass to middleware using comma ,
as follows:
Route::get('/mid', ['middleware' => 'roles:super,admin', function () {
// ^ note this
return "done";
}]);
note that, this won't send parameters as an array, so you can't loop over $roles
unless you use your passed parameters as ellipsis parameters as follows :
public function handle($request, Closure $next, ...$roles)
rather, you will need to use a single parameter for each role:
public function handle($request, Closure $next, $role1, $role2) // .... and so on
Route:
Route::get('/access', ['middleware' => 'hasroles:super,admin', function () {
}]);
passing one parameter to check user have created permission in my cause
Route::middleware('admin')->namespace('Admin')->prefix('admin')->group(function(){
Route::get('/home', 'MainController@getIndex')->name('admin.index')->middleware("hasrole:create");
Middleware:
1.Using Parameters
public function handle($request, Closure $next, $parm1, $parm2){}
2.Using var-arg
public function handle($request, Closure $next, $parm1, $parm2){}
public function handle($request, Closure $next, ...$parm1){}
Two-way Middleware Use
1: Register routeMiddleware
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'hasrole' => \Illuminate\Auth\Middleware\HasRole::class,
Using:
Route::get('admin/profile', function () {
})->middleware('hasrole');
2: Not Register in routeMiddleware
Using:
use App\Http\Middleware\HasRole;
Route::get('admin/profile', function () {
//
})->middleware(HasRole::class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With