You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<?php
namespace App\Http\Middleware;
use Closure;
class EnsureUserHasRole
{
/**
* 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);
}
}
If I have many routes and all of them need to use the role middleware with certain role:
Route::middleware(['role:role_x'])->group(function () {
Route::get
Route::get
Route::post
Route::put
Route::get
// and many more
Route::middleware(['role:role_x,role_y'])->group(function () {
// specific routes that need another role in addition to role_x
Route::get
Route::post
});
});
This is an example with only 2 roles, but sometimes it can get to more and then you'd have to manually assign it to many individual route group
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Sometimes there are many routes that need to use come Middleware with certain parameter, but certain routes inside also need extra parameters.
Example - from the docs: https://laravel.com/docs/9.x/middleware#middleware-parameters
If I have many routes and all of them need to use the
role
middleware with certain role:This is an example with only 2 roles, but sometimes it can get to more and then you'd have to manually assign it to many individual route group
Beta Was this translation helpful? Give feedback.
All reactions