user5500750 user5500750 - 6 months ago 40
PHP Question

Multiple dynamic url redirect in Laravel

I have looked at many similar questions bu they don't approach the real problem. I would like to redirect a user to a certain url just after login depending on a condition about the user.

I know this can be archieved with a middleware so I have tried this in app\Http\Middleware\RedirectIfAuthenticated.php

class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::User()->check()) {
$redirect = '/client';
if (Auth::user()->hasRole('admin')){
$redirect = '/admin';
}
return redirect($redirect);
}
return $next($request);
}
}


I realise now this will not work just after login. I'd like to redirect a user depending whether he/she is an admin or a client. I know I could use: protected $redirectPath = '/url/to/redirect'; but I have multiple pages to redirect to.

What is the best way to do this?

Answer

You could over-write the redirect method offered up by the trait in app/Http/Controllers/Auth/AuthController.php

public function redirectPath()
{
    if (Auth::user()->hasRole('admin')){
        return '/admin';
    }

    return '/client';
}

Put that in your AuthController.php.