Laravel Nova Redirect to a custom path after login

2020-02-14 20:47发布

问题:

I need to redirect user after login to a different place according to its role.

The logic is simple. I tried to put it in redirectPath() function in Nova LoginController.php, but I have a very wired behavior - sometimes after login I reach the right place, sometimes Nova redirects me to panel.

Any idea?

回答1:

After a couple of hours of investigation, I figured out that the solution is quite simple.

All I had to do is to add the following function to nova LoginController:

protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    $redirectPath = $this->redirectPath();
    redirect()->setIntendedUrl($redirectPath);

    return redirect()->intended($redirectPath);
}

Explanation:

This function is implemented in trait AuthenticatesUsers.

intended function (member of Redirector class) create a redirect response, based on previously intended location, and if not exists - on given url.

If no url.intended is set in session, user will be redirected to url generated by LoginController::redirectPath. However, if there an entry of url.intended does exist in session, we need to delete it in order to force redirecting user to the url we are interested in.

The only problem which I see is that we loose the feature of redirecting user to the same page he was before he was logged out. So it is a simple matter of choice as a developer...