我正在顯示用戶會話何時到期的前端倒計時,我想請求剩下的時間而不更新它。Laravel會話提出請求,但不更新會話到期
這是我到目前爲止有:
$ttl = Redis::ttl(config('cache.prefix') . ':' . Session::getId());
return response()->json($ttl);
每次這個請求的TTL被重置爲session.lifetime
值時間。
我正在顯示用戶會話何時到期的前端倒計時,我想請求剩下的時間而不更新它。Laravel會話提出請求,但不更新會話到期
這是我到目前爲止有:
$ttl = Redis::ttl(config('cache.prefix') . ':' . Session::getId());
return response()->json($ttl);
每次這個請求的TTL被重置爲session.lifetime
值時間。
我解決了這個通過擴展StartSession
中間件:
class StartSession extends \Illuminate\Session\Middleware\StartSession
{
public function terminate($request, $response)
{
if (!$request->is('auth/ping')) {
parent::terminate($request, $response);
}
}
}
哪裏auth/ping
是我不希望會話保存的路由。
我然後在應用程序容器作爲一個單獨註冊的這一點,所以終止方法解決同一實例:
在AppServiceProvider->register
:
$this->app->singleton('App\Http\Middleware\StartSession');
app/Providers/RouteServiceProvider.php中現有的mapWebRoutes()方法看起來像這樣。
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
您可以簡單地添加類似以下內容到方法,或者你可以重複上面它加載routes.php文件的代碼,並刪除Web中間件。
$router->get('session-ttl', function() {
return response()->json(
\Redis::ttl(config('cache.prefix') . ':' . cookie(config('session.cookie')));
);
});
或者
$router->group([
'namespace' => $this->namespace
], function ($router) {
require app_path('Http/routes_wo_web.php');
});
感謝你們,我沒有看過'RouteServiceProvider'。我注意到這個項目最初是用5.1創建的,然後升級到5.2,所以它看起來有點不同。我已經擴展了'StartSession'中間件的'terminate'方法來檢查請求是否匹配路徑。我認爲這是更簡單的解決方案,因爲如果需要的話,我仍然可以使用該路由中的會話來獲取任何值。 – Petecoop
會話的東西是由Illuminate\Session\Middleware\StartSession
中間件處理,它位於web
中間件組中。
最簡單的解決方案是將您的路線放置在標準的web
中間件組之外。
如果您需要任何其他web
中間件,您可以將它們添加回路由。
要在路線實際使用的會話,你有兩個選擇:
handle
方法只需要return $next($request)
)我認爲推薦的解決方案應該是在中間件中完成。
謝謝,我的項目是用Laravel 5.1創建的,升級到5.2,所以它在全局中間件而不是'web'組中。看到我的答案 - 我繼續擴展當前的'StartSession'中間件並更改'terminate'方法。 – Petecoop
您正在使用哪個會話驅動程序? –
此外,當然你可以只需要一個倒數等於請求發起時的會話長度? –
我正在使用Redis。是的,我可以這樣做,但如果另一個選項卡打開,重置它不會更新。 – Petecoop