DEV Community

Discussion on: Multiple role-based authentication in Laravel

Collapse
 
martin_betz profile image
Martin Betz • Edited

May I propose a refactor for the handle method? You could save some duplications by flipping the logic. If you first ask for if the user is not logged in, redirect to login you catch this case once and can skip it for everything that follows. Also, instead of elseelse, you can simply use ifif. If a case proves true, you return something and the function stops, so you do not need an else. This reduces cognitive load.

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');
    }
}
Collapse
 
kaperskyguru profile image
Solomon Eseme

This is great, thanks for your contribution, I will refactor immediately.

Collapse
 
kaperskyguru profile image
Solomon Eseme

Updated now..

Collapse
 
picwellwisher12pk profile image
Amir Hameed

What about switch statement?

Collapse
 
martin_betz profile image
Martin Betz

Yes, switch would cut some duplicate lines. I would still propose the lookup array pattern as recommended in this extra comment as it is a lot easier to add and cut arguments and is super easy to read.

Thread Thread
 
picwellwisher12pk profile image
Amir Hameed

These if statements could also be one-liners to save some more characters and space.

Thread Thread
 
martin_betz profile image
Martin Betz

Yes, but there still would be lots of repetitions even in short-form. Maybe I can write an own article soon about possible refactorings so that people can learn and compare. The original poster went with the simple if solution but there are multiple ways to make it shorter and easier to maintain.

Thread Thread
 
picwellwisher12pk profile image
Amir Hameed

Indeed.
Tell me where can I start a new discussion?

Thread Thread
 
martin_betz profile image
Martin Betz

Just put a comment on the root of this article: dev.to/kaperskyguru/multiple-role-...