auto logout when session expires laravel code example

Example 1: auto logout when session expires laravel

# Session lifetime in minutes
SESSION_LIFETIME=10

Example 2: auto logout when session expires laravel

class LoginController extends Controller
{
  // ...
  protected function authenticated(Request $request, $user)
  {
    $user->last_seen_at = Carbon::now()->format('Y-m-d H:i:s');
    $user->save();
  }
}

Example 3: auto logout when session expires laravel

class Kernel extends HttpKernel
{
  // ...
  protected $middlewareGroups = [
    'web' => [
      // ...
      \App\Http\Middleware\SessionTimeout::class,
  ],
}

Example 4: auto logout when session expires laravel

class SessionTimeout
{
  public function handle($request, Closure $next)
  {
    // If user is not logged in...
    if (!Auth::check()) {
      return $next($request);
    }
 
    $user = Auth::guard()->user();
 
    $now = Carbon::now();
 
    $last_seen = Carbon::parse($user->last_seen_at);
 
    $absence = $now->diffInMinutes($last_seen);
 
    // If user has been inactivity longer than the allowed inactivity period
    if ($absence > config('session.lifetime')) {
      Auth::guard()->logout();
 
      $request->session()->invalidate();
 
      return $next($request);
    }
 
    $user->last_seen_at = $now->format('Y-m-d H:i:s');
    $user->save();
 
    return $next($request);
  }
}

Example 5: auto logout when session expires laravel

class AddLastSeenToUsersTable extends Migration
{
  public function up()
  {
    Schema::table('users', function (Blueprint $table) {
      $table->timestamp('last_seen_at')->nullable();
    });
  }
 
  public function down()
  {
    Schema::table('users', function (Blueprint $table) {
      $table->dropColumn('last_seen_at');
    });
  }
}

Tags:

Misc Example