当会话在Laravel中过期时,将用户重定向到登录页面 [英] Redirect user to login page when session expires in Laravel
问题描述
如果用户会话已过期,我正尝试将其重定向回登录页面.我正在使用Laravel 5.5.我已经编辑了RedirectIfAuthenticated
文件,以在handle
函数中包含以下代码:
I am trying to redirect a user back to the login page if their session has expired. I am using Laravel 5.5. I have edited my RedirectIfAuthenticated
file to include the following code in the handle
function:
if (!Auth::check()) {
return redirect()->route('login', ['account' => 'demo']);
}
当我这样做时,我收到以下错误消息:
When I do this, I am receiving the following error message:
缺少[路由:登录] [URI:/]所需的参数.
Missing required parameters for [Route: login] [URI: /].
我的login
路由位于子域路由组内,这就是为什么我要传递account
参数的原因.这是我在web.php
My login
route is inside a subdomain route group which is why I am passing the account
parameter. Here is part of my code in web.php
// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
Route::get('/', 'LoginController@show')->name('login');
}
这是我的LoginController@show
代码:
/*
* Show the login form
*/
public function show($account) {
// Validate this is a valid subdomain
$organization = Organization::where('subdomain', $account)->first();
if ($organization) {
return view('login');
} else {
return 'This account does not exist.';
}
}
我没有尝试过任何方法.即使我传入了必需的参数,我仍然收到完全相同的错误消息.
Nothing I have tried works. I keep getting the exact same error message even though I am passing in the required parameters.
错误页面的屏幕截图:
仔细研究 Whoops!错误页面后,我看到了,protected function unauthenticated
是引起问题的原因:
After a little digging around the Whoops! error page, I see this, protected function unauthenticated
is what is causing the problem:
如何覆盖此函数以添加缺少的参数?
How do I override this function to add the missing parameter?
推荐答案
您可以在app/Exceptions/Handler.php
文件中覆盖unauthenticated()
方法以添加缺少的route参数.
You can override the unauthenticated()
method in your app/Exceptions/Handler.php
file to add the missing route parameter.
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest(route('login', ['account' => $request->route('account')]));
}
}
这篇关于当会话在Laravel中过期时,将用户重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!