DEV Community

Discussion on: Multiple role-based authentication in Laravel

Collapse
 
martin_betz profile image
Martin Betz • Edited

And here's another refactor to make it even conciser and easier to read and change. It is using a lookup array to isolate changes (just add a new item to the array for a new role) and have one execution path (one redirect line instead of 5).

public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        if (Auth::user()->role == 3) {
            return $next($request);
        }

        $destinations = [
            1 => 'superadmin',
            2 => 'admin',
            4 => 'team',
            5 => 'academy',
            6 => 'scout',
        ];

        return redirect(route($destinations[Auth()::user()->role]));
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kaperskyguru profile image
Solomon Eseme

I'm Having errors after implementing this.
I logged in as academy then try to visit the admin dashboard by typing the route to it in the browser and i got this -> "Call to undefined method Illuminate\Auth\AuthManager::user()"

Collapse
 
computermaverick profile image
⚓Timmy Iwoni ⚓

In Martin's implementation there's a typo of the parenthesis when calling the Auth facade... So instead of Auth()::user()->role, it should be Auth::user()->role

Thread Thread
 
kaperskyguru profile image
Solomon Eseme

Oh that's true.. I will fix that..

Collapse
 
martin_betz profile image
Martin Betz

I'll replicate it soon, probably I just have a typo somewhere.

Thread Thread
 
kaperskyguru profile image
Solomon Eseme

Sure. I will be expecting.

Collapse
 
kaperskyguru profile image
Solomon Eseme

Wow.. it's getting more clean and clear.. Thanks for the update.

Collapse
 
baronsindo profile image
𝙹𝚒𝚋𝚛āʾī𝚕 ⚡

a comment that make me awkwardly happy