Laravel middleware with multiple roles
Asked Answered
H

3

34

I've been running into some issues with Laravel's middleware. Let me tell you the basic idea of what I'm trying to accomplish:

Registered users on the site will have one of four roles:

  1. Student (default): can access 'index' and 'show' views
  2. Approver: can access previous, plus 'overview', 'update'
  3. Editor: can access previous, plus 'create', 'edit' and 'store'
  4. Admin: can access everything

fyi: 'overview' is sort of an index view, but only for approver role and higher

What would you guys suggest is the best way to go about doing this? This is what I've done so far, but it doesn't seem to work:


Kernel.php

protected $middlewareGroups = [
...
    'approver+' => [
        \App\Http\Middleware\Approver::class,
        \App\Http\Middleware\Editor::class,
        \App\Http\Middleware\Admin::class,
    ],
];

protected $routeMiddleware = [
...
    'student' => \App\Http\Middleware\Student::class,
    'approver' => \App\Http\Middleware\Approver::class,
    'editor' => \App\Http\Middleware\Editor::class,
    'admin' => \App\Http\Middleware\Admin::class,
];

Http\Middleware\Admin.php

public function handle($request, Closure $next)
{
   if (Auth::check())
   {

        if(Auth::user()->isAdmin())
        {
            return $next($request);
        }
   }

    return redirect('login');
}

The 'User' Eloquent model:

public function isAdmin()
{
    if($this->role_id === 4)
    { 
        return true; 
    } 
    else 
    { 
        return false; 
    }
}

I've done the exact same in the Approver and Editor middleware files, and in the isApprover and isEditor functions in the User model, only edited the checked value in the if-statement to 2 and 3 respectively.

Finally, here's what I've done in my routes\web file:

Route::get('scholen', 'SchoolsController@index');
Route::get('admin/scholen/overzicht', 'SchoolsController@overview')->middleware('approver+');
Route::get('admin/scholen/maken', 'SchoolsController@create')->middleware('approver+');
Route::post('scholen', 'SchoolsController@store')->middleware('approver+');
Route::get('scholen/{id}', 'SchoolsController@show');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController@edit')->middleware('admin');
Route::patch('admin/scholen/{id}', 'SchoolsController@update')->middleware('admin');
Route::delete('admin/scholen/{id}', 'SchoolsController@destroy')->middleware('admin');

It isn't all exactly on point yet, but I got stuck since when I log in as a user with Approver rights and try to access the schools overview, it redirects me back to the home page.

In general, it just feels like I'm working much too chaotically and not right at all, could somebody give me advice on how to do it more efficiently?

Thank you very much in advance!

Hectorhecuba answered 10/5, 2017 at 19:59 Comment(0)
S
92

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');
Stator answered 10/5, 2017 at 20:41 Comment(7)
I figured I was making it much too complicated :) That seems to work fine, thank you very much!Hectorhecuba
3 dots "..." saved my life :)Vanderpool
that operator has name wiki.php.net/rfc/spread_operator_for_arraySimas
What if I want to group admin and editor routes and have different prefix for both? If editor logs in the URL should be editor/dashboard and if the admin logs in the URL should be admin/dashboard. What can we achieve it?Dubiety
@Vanderpool This funny 3 dots "..." is called Constant expressions which is available => PHP 5.6.x ;) Funny huh! :pBrierroot
I am using laravel 7.x and for me, it's coming in a string. Please help meLaminous
great job doing such clean middleware, thank you!Tonsorial
C
5

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);
Creation answered 29/12, 2020 at 16:50 Comment(0)
H
2

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');
    }
}
Hard answered 18/9, 2020 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.