问题描述
我正在尝试返回另一条路线,因为在我的情况下,登录它是一个模态页面,当会话过期时,返回到这条路线但它不存在。我不知道我会怎么做。
我可以在网络上看到这个:if(Auth::check()){ return route('/')}
但我不知道我把这段代码放在哪里。
我也可以看到:在“App\Exception\Handler”中输入:
if ($exception instanceof AuthenticationException) {
return redirect('/');
}
我该怎么做?
谢谢你的帮助
解决方法
您可以创建一个路由来检查会话,每分钟它都会检查会话是否存在。 你可以这样使用:
刀片部分:
@if (Auth::user())
<script>
$(function() {
setInterval(function checkSession() {
$.get('/is-logged-in',function(data) {
// if session was expired
if (!data.isLoggedIn) {
// redirect to login page
// or,may be better,just reload page
location.reload();
}
});
},60000); // You can change it
});
</script>
@endif
路线:
Route::get('is-logged-in','Auth\AuthController@checkSession');
控制器:
public function checkSession()
{
return Response::json(['isLoggedIn' => Auth::check()]);
}
,
Laravel 可能已经有了你需要的东西。看看 App\Http\Middleware\Authenticate
类。这是一个中间件,如果会话已过期,它会将用户重定向到“登录”命名路由(默认情况下)。
默认情况下,您放入 routes/web.php
的路由均不受此中间件保护,但您可以更改此设置。
方法 1:在控制器的构造函数中添加一个 auth
中间件:
public function __construct()
{
$this->middleware('auth');
}
方法 2:为您的其中一个路由添加一个 auth
中间件:
Route::get('profile',function () {
// Only authenticated users may enter...
})->middleware('auth');
方法三:将所有受保护的路由加入组:
Route::group(['middleware' => ['auth']],function () {
// All your protected routes go here
});
然后您可以轻松更改 URL,该 URL 将用于重定向会话过期(未经过身份验证)的用户。只需编辑 App\Http\Middleware\Authenticate::redirectTo()
方法并返回您的网址,例如:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('yourLoginRouteName');
}
}