In laravel auth middleware i create session variable and store the the last entering time like
class Authenticate extends Middleware
{
public function handle($request, Closure $next, ...$guards)
{
if (auth()->check()) {
session()->put('activity_time', now()->toDateTimeString());
}
return parent::handle($request, $next, ...$guards);
}
protected function redirectTo(Request $request): ?string
{
if ($request->expectsJson()) {
return null;
}
return route('root');
}
}
In route
Route::get('/', [AuthController::class, 'index'])->middleware('guest')->name('root');
Route::middleware(['auth'])->group(function () {
Route::resource('home', HomeController::class);
Route::resource('student', StudentController::class);
});
in above route we do any operations in side the auth group that time session last active is updated?
and i create another middelware for check the time diffrence like
class CheckLastActivityTime
{
public function handle(Request $request, Closure $next)
{
$lastActivity = session()->get('activity_time');
// var_dump($lastActivity); die();
if ($lastActivity) {
$lastActivity = Carbon::parse($lastActivity);
if (Carbon::now()->diffInMinutes($lastActivity) > 5) {
auth()->logout();
session()->invalidate();
session()->regenerateToken();
return redirect('root')->with('error', 'Your session has expired. Please log in again.');
}
}
return $next($request);
}
}
And this middleware register in kernel
protected $middleware = [
// ...
AppHttpMiddlewareCheckLastActivityTime::class,
];
and i dd the $lastActivity in the middleware it’s show null, how we can track the time and logout the user?
2
Answers
move your CheckLastActivityTime::class from the:
to the:
then apply the middleware to the routes same as you do with the auth middleware.
Now the session will be available in the middleware, before it was not as it probably wasn’t initiated yet.
If you want to just destroy the session it automatically destroy after the 120 min
you can see here
config/session.php
‘lifetime’ => env(‘SESSION_LIFETIME’, 120),
you can increase and decrease the time from here.