当会话在 Laravel 后过期时将用户重定向到登录页面
Redirect user to login page when session expires in Laravel
如果用户的会话已过期,我正在尝试将用户重定向回登录页面。我正在使用 Laravel 5.5。我已经编辑了我的 RedirectIfAuthenticated
文件以在 handle
函数中包含以下代码:
if (!Auth::check()) {
return redirect()->route('login', ['account' => 'demo']);
}
执行此操作时,我收到以下错误消息:
Missing required parameters for [Route: login] [URI: /].
我的 login
路由在子域路由组内,这就是我传递 account
参数的原因。这是我在 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.';
}
}
我试过的都没有用。即使我传递了必需的参数,我仍然收到完全相同的错误消息。
更新#1
错误页面截图:
更新#2
在 糟糕! 错误页面稍作研究后,我看到了这个,protected function unauthenticated
是导致问题的原因:
如何覆盖此函数以添加缺少的参数?
您可以覆盖 app/Exceptions/Handler.php
文件中的 unauthenticated()
方法以添加缺少的路由参数。
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 5.5。我已经编辑了我的 RedirectIfAuthenticated
文件以在 handle
函数中包含以下代码:
if (!Auth::check()) {
return redirect()->route('login', ['account' => 'demo']);
}
执行此操作时,我收到以下错误消息:
Missing required parameters for [Route: login] [URI: /].
我的 login
路由在子域路由组内,这就是我传递 account
参数的原因。这是我在 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.';
}
}
我试过的都没有用。即使我传递了必需的参数,我仍然收到完全相同的错误消息。
更新#1
错误页面截图:
更新#2
在 糟糕! 错误页面稍作研究后,我看到了这个,protected function unauthenticated
是导致问题的原因:
如何覆盖此函数以添加缺少的参数?
您可以覆盖 app/Exceptions/Handler.php
文件中的 unauthenticated()
方法以添加缺少的路由参数。
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')]));
}
}