我有一个页面,用户需要登录才能点击按钮,如果他们没有登录,他们会被带到登录页面进行登录。问题是登录后他们被重定向到主页。我希望将它们重定向回登录前的页面,但无法使其正常工作。
登录方法仍然是100%标准。我试过编辑这个功能,但没有运气。
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
答案 0 :(得分:5)
如果您只是想将用户重定向到其他页面而不是/ home,只需定义一个
即可protected $redirectTo = 'your-different-route'; // i.e. '/admin'
位于AuthController的顶部
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = 'admin/';
......
这应该覆盖默认路线 无论如何,在你想要深入挖掘登录系统
return redirect()->intended($this->redirectPath());
是关键。仰望intended
方法(Illuminate \ Routing \ Redirector)你会发现类似的东西
public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
$path = $this->session->pull('url.intended', $default);
return $this->to($path, $status, $headers, $secure);
}
然后,您将注入预定的方法$this->redirectPath()
,定义为
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
基本上,每次用户执行登录时,系统都会检查是否存在不同的intended
路由,如果不是,则使用默认路由(/ home)。您可以将默认重定向路由更改为非常redirectPath()方法,但请注意,这是laravel框架的一部分,因此每次laravel获取更新时,您可能会丢失更改。更安全的解决方案就像我上面提到的几行一样,覆盖了AuthController中的redirect
(上传和赢得的东西不会影响控制器)。
修改强>
如果您想为每次登录设置自定义重定向路由,Laravel会提供一种方便的方法来实现开箱即用,并且,我们将再次使用intended()
方法。无论您将用户重定向到登录页面,请使用getLogin()
方法,您需要更改默认重定向,例如
return view('auth.login');
到
return Redirect::guest('auth.login') //assuming that auth.login is your login view
通过这个简单的修复,您仍然将用户重定向到登录页面,但改为使用guest()
方法:
public function guest($path, $status = 302, $headers = array(), $secure = null)
{
$this->session->put('url.intended', $this->generator->full());
return $this->to($path, $status, $headers, $secure);
}
相当简单,但是,除了标准重定向to()
之外,它在实际重定向之前设置为session
intended
变量等于当前网址,即您想要的页面重定向到。这就是为了节省你的一天
最后,在postLogin()
方法中,只需设置
return Redirect::intended('default-route');
如果会话中未提供预期位置,则需要传递默认值。请注意,这只是一个安全加,因为默认情况下,您的postLogin()
已经
redirect()->intended($this->redirectPath());
默认使用redirectPath()
,但现在Redirect::guest()
应提供intended
值。
答案 1 :(得分:0)
您可以使用Redirect-> back()方法:
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->back();
}
虽然通常最好在Auth中间件中处理此问题。
可以在Laravel website上找到更多信息。
答案 2 :(得分:0)
请检查您可能需要添加的this解决方案
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/player';
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
//
return redirect()->route('homePlayer') ;
}
在您的LoginController.php中