Home > other >  Laravel 8 | Redirect according to role after login
Laravel 8 | Redirect according to role after login

Time:03-07

i am using Laravel as Framework, I'm creating a page with various types of roles, I have the authentication controlled with a middleware, so far so good. My problem is with the redirection after login. I have my users table with a field called "Rol" I need, before entering the system, to verify that "Rol" has my user and according to that, I am redirected to a dashboard or another.

Route::get('/dashboard', [GeneralController::class,'redirectAfterLogin'])->middleware(['auth'])->name('dashboard');

i am using this in the routes. i have un general controller with a function called "redirectAfterLogin"

This is my function

public function redirectAfterLogin(Request $request){
    $role = $request->user()->role;
    switch ($role) {
        case 'Admin':
            return redirect(route('admin/dashboard'));
            break;
        case 'SubAdmin':
            return redirect(route('cita/addAppointment'));
            break;
        case 'Medico':
            return redirect(route('cita/pattientsToday'));
            break;
        case 'Paciente':
            return redirect(route('cita/decideLevel'));
            break;
        
        default:
            # code...
            break;
    }
}

This works for me, but I don't think it's the right way. I know that with a middleware you can control this, but I don't know how, or what else should change for that middleware to work

class RedirectIfAuthenticated
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure(\Illuminate\Http\Request): 
 (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
 * @param  string|null  ...$guards
 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
 */
public function handle(Request $request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            if($request->user()->role == "Admin"){
                return "/AdminDashboard";
            }else{
                return "/GeneralDashboard";
            }
        }
    }
    return $next($request);
}
}

This middleware is supposed to handle redirects but no matter how I do it it doesn't happen

CodePudding user response:

Your problem is return string, you need add return redirect(url_name)

Try this code, I think she will help you.

    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
               switch (Auth::guard($guard)->user()->role){
                   // Redirect Admin Dashboard
                  case 'Admin':
                    return redirect('/AdminDashboard');
                    break;

                  // If need any Roles for example:
                  case: 'RoleName':
                  return redirect('url');
                  break;
                  default: return  redirect('/GeneralDashboard');
               }
            }
        }
        return $next($request);
    }

CodePudding user response:

Ok, I managed to find the solution. I implemented a predesigned login with Brezze (I think that's how it is written) The point is that to redirect it creates a controller called "AuthenticatedSessionController" This has the "store" method where the verification of the session data is done and if they are correct it is redirected to "HOME" This is where we put our logic, in my case I did it with a switch.

class AuthenticatedSessionController extends Controller
{
/**
 * Handle an incoming authentication request.
 *
 * @param  \App\Http\Requests\Auth\LoginRequest  $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function store(LoginRequest $request)
{
    $request->authenticate();

    $request->session()->regenerate();

    $role = $request->user()->role;
    switch ($role) {
        case 'Admin':
            return redirect(route('admin/dashboard'));
            break;
        case 'SubAdmin':
            return redirect(route('cita/addAppointment'));
            break;
        case 'Medico':
            return redirect(route('cita/pattientsToday'));
            break;
        case 'Paciente':
            return redirect(route('cita/decideLevel'));
            break;
    }
}

Now, there is also a middleware called "RedirectIfAuthenticated", it takes care of the redirects after you are logged in and change the url to the root. Let me explain, suppose I have 2 users Admin and Public, each one has a different HOME, when logging in who redirects you to the correct HOME, it is the "AuthenticatedSessionController" controller, and if after logging in you write in the URL "http://My_domain/" (i mean, the root) will be the middleware "RedirectIfAuthenticated" who makes the redirection to the correct HOME. The controller only works when you login, the other times the middleware will do it.

In my middleware i have this.

class RedirectIfAuthenticated
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure(\Illuminate\Http\Request): 
(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
 * @param  string|null  ...$guards
 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
 */
public function handle(Request $request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            $role = $request->user()->role;
            switch ($role) {
                case 'Admin':
                    return redirect(route('admin/dashboard'));
                    break;
                case 'SubAdmin':
                    return redirect(route('cita/addAppointment'));
                    break;
                case 'Medico':
                    return redirect(route('cita/pattientsToday'));
                    break;
                case 'Paciente':
                    return redirect(route('cita/decideLevel'));
                    break;
            }
        }
    }
    return $next($request);
}

Both the controller and the middleware are created by Brezze, I don't know how it will work with other login templates. But at least in Brezze I think this would be the correct way to redirect.

  • Related