当 Laravel 中的会话过期时将用户重定向到登录页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47274200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect user to login page when session expires in Laravel
提问by three3
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:
如果他们的会话已过期,我试图将用户重定向回登录页面。我正在使用 Laravel 5.5。我编辑了我的RedirectIfAuthenticated
文件以在handle
函数中包含以下代码:
if (!Auth::check()) {
return redirect()->route('login', ['account' => 'demo']);
}
When I do this, I am receiving the following error message:
当我这样做时,我收到以下错误消息:
Missing required parameters for [Route: login] [URI: /].
缺少 [Route: login] [URI: /] 的必需参数。
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
我的login
路由位于子域路由组内,这就是我传递account
参数的原因。这是我的代码的一部分web.php
// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
Route::get('/', 'LoginController@show')->name('login');
}
And here is my LoginController@show
code:
这是我的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.
我试过的任何东西都不起作用。即使我传递了所需的参数,我仍然收到完全相同的错误消息。
Update #1
更新 #1
Screenshot of error page:
错误页面截图:
Update #2
更新 #2
After a little digging around the Whoops!error page, I see this, protected function unauthenticated
is what is causing the problem:
在对Whoops稍作挖掘之后!错误页面,我看到了这个,protected function unauthenticated
是导致问题的原因:
How do I override this function to add the missing parameter?
如何覆盖此函数以添加缺少的参数?
回答by Camilo
You can override the unauthenticated()
method in your app/Exceptions/Handler.php
file to add the missing route parameter.
您可以覆盖文件中的unauthenticated()
方法app/Exceptions/Handler.php
以添加缺少的路由参数。
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')]));
}
}