L5:登录后更改重定向

L5 : Changing the redirection after a login

我想在 login/logout 之后更改重定向。

在我的Auth/AuthController我定义了

protected $redirectAfterLogout = '/';
protected $redirectTo = '/';

注销路由很好:root,但登录重定向仍然/home.....

使用protected $redirectPath ='/'并没有解决我的问题

AuthController 中,添加 2 个函数 getLogoutpostLogin 来处理 login/logout 请求。之后,Laravel会为你处理魔法。

 public function postLogin(Request $req){
    //Validate input
    $this->validate($req,[
        'email' => 'required', 'password' => 'required'
    ]);

    $credentials = $req->only('email','password');

    if($this->auth->attempt($credentials,$req->has('remember'))){
        return redirect('articles');
    }
    return redirect('auth/login')
                ->withInput($req->only('email'))
                ->withErrors([
                    'email' => 'Something wrong'
                ]);
}

 public function getLogout(){
    $this->auth->logout();
    return redirect('articles');
}

RedirectIfAuthenticated中间件尝试在以下函数中设置重定向路径,

public function handle($request, Closure $next)
{
    if ($this->auth->check())
    {
        return new RedirectResponse(url('/home'));
    }

    return $next($request);
}

这基本上是检查 user 是否登录重定向到 home

RedirectIfAuthenticated

public function handle($request, Closure $next) {

    if ($this->auth->check())
    {
        return new RedirectResponse(url('/'));
    }

    return $next($request);
}

登录 post 处理程序的默认实现重定向到用户在被重定向到登录页面之前打算访问的 URL。

如果 Laravel 无法找到预期的 URL 它会从 AuthenticatesAndRegistersUsers 特征传递 redirectPath() 的输出,如下:

/**
 * Get the post register / login redirect path.
 *
 * @return string
 */
public function redirectPath()
{
    if (property_exists($this, 'redirectPath'))
    {
        return $this->redirectPath;
    }

    return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}

如您所见,它会查找属性 redirectPathredirectTo。我不确定为什么两者都有;也许对于旧版本的 BC。

在您的控制器中设置这些属性中的任何一个就足够了。也就是说,如果您想以不同的方式实现它,您也应该能够在您的控制器中覆盖此方法。

需要注意的一件事是,仅当 Laravel 找不到预期的 url/path 时才会调用此方法。例如,如果您访问 /home 并被重定向到登录页面,那么 /home 就是您想要的 URL,因此您将被重定向到那里。

强制执行此操作的唯一方法是通过覆盖控制器中的方法来替换 postController 的实现,或者首先设置 url.intended 会话变量。

// Obviously add namespaces and use statements 

class AuthController extends Controller {
    use AuthenticatesAndRegistersUsers {
        postLogin as traitPostLogin;
    }

    protected $redirectTo = 'some-page';

    function postLogin(Request $request) {
      session('url.intended', $this->redirectTo);

      return $this->traitPostLogin($request);
    }
}