假设我有一个页面 A,其中正在使用 auth 中间件。由于没有登录,它被重定向到登录页面。
在登录页面上,我有自定义的 ajax 登录系统。成功登录后,我想重定向到具有相同 url 的页面 A,以便可以完成操作。
我的登录代码是这样的:
public function postLogin(Request $request)
{
$auth = false;
$errors = [];
$inputs = $request->all();
$validator = $this->validator($inputs);
if ($validator->fails()) {
return response()->json([
'auth' => false,
'intended' => URL::previous(),
'errors' => $validator->errors()
]);
}
$user = User::where('email', $request->get('email'))->first();
if ($user && $user->is_active == 0) {
$errors[] = "This account has been deactivated";
} else if ($user && $user->confirm_token != null) {
$errors[] = "Please verify your email in order to login";
} else {
$credentials = ['email' => $request->get('email'), 'password' => $request->get('password'), 'is_active' => 1];
if (Auth::attempt($credentials, $request->has('remember'))) {
$auth = true;
} else {
$errors[] = "Email/Password combination not correct";
}
}
if ($request->ajax()) {
return response()->json([
'auth' => $auth,
'intended' => URL::previous(),
'errors' => $errors
]);
}
return redirect()->intended(URL::route('dashboard'));
}
我试图通过 url()->previous() 获取以前的 url,但它返回登录页面 url。有人可以指导我吗?任何改进/帮助将不胜感激。
我正在使用 Laravel 5.4
最佳答案
我在这里有一个非常相似的问题:Ajax Auth redirect on Laravel 5.6
正如@aimme ( https://stackoverflow.com/users/1409707/aimme ) 指出的,Ajax 调用是无状态的,所以基本上你不能与后端交互。
他的建议和我的建议是传入要重定向到的预期页面的 URL,或者在您的情况下,您可以通过 post 参数传递给它,例如:
return response()->json([
'auth' => false,
'intended' => $request->intended,
'errors' => $validator->errors()
]);
关于ajax - Laravel Ajax 登录,成功后重定向到上一个网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50794892/