Laravel middleware with multiple roles
This is a complement to the fafich's response.
Instead of using FOREACH you use in_array in IF, like this:
if (! in_array($user->hasRole($role), $roles) {
// returns if you dont have permission
}
return $next($request);
Complete your Handle function For Every Login Session request
public function handle($request, Closure $next)
{
if (! Auth::check()) {
return redirect()->route('login');
}
if (Auth::user()->role == 1) {
return redirect()->route('superadmin');
}
if (Auth::user()->role == 5) {
return redirect()->route('academy');
}
if (Auth::user()->role == 6) {
return redirect()->route('scout');
}
if (Auth::user()->role == 4) {
return redirect()->route('team');
}
if (Auth::user()->role == 3) {
return $next($request);
}
if (Auth::user()->role == 2) {
return redirect()->route('admin');
}
}
You should't have a separate middleware for each role. It will get very messy very fast. It would be better to have a single role checking middleware that can check against any role passed to it.
Http\Kernel.php
protected $routeMiddleware = [
...
'role' => \App\Http\Middleware\Role::class,
];
Http\Middleware\Role.php
public function handle($request, Closure $next, ... $roles)
{
if (!Auth::check()) // I included this check because you have it, but it really should be part of your 'auth' middleware, most likely added as part of a route group.
return redirect('login');
$user = Auth::user();
if($user->isAdmin())
return $next($request);
foreach($roles as $role) {
// Check if user has the role This check will depend on how your roles are set up
if($user->hasRole($role))
return $next($request);
}
return redirect('login');
}
Finally in your web routes
Route::get('admin/scholen/overzicht', 'SchoolsController@overview')->middleware('role:editor,approver');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController@edit')->middleware('role:admin');