Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

Session Management

The package provides comprehensive session management capabilities, allowing you to view and manage active user sessions.

Getting Active Sessions

Get all active sessions for a user:

1$user = User::find(1);
2 
3// Get active sessions collection
4$activeSessions = $user->getActiveSessions();
5 
6// Get count of active sessions
7$sessionCount = $user->getActiveSessionsCount();
8 
9// Get active sessions query builder (for further filtering)
10$activeSessionsQuery = $user->activeSessions();

Revoking Sessions

Revoke a Specific Session

1$user = User::find(1);
2$sessionId = 123;
3 
4if ($user->revokeSession($sessionId)) {
5 // Session revoked successfully
6}

Revoke All Other Sessions

Keep the current device logged in while logging out all other devices:

1$user = User::find(1);
2$currentDeviceId = DeviceFingerprint::generate(request());
3 
4$revokedCount = $user->revokeAllOtherSessions($currentDeviceId);
5// Returns the number of sessions revoked

Revoke All Sessions

Log out the user from all devices:

1$user = User::find(1);
2 
3$revokedCount = $user->revokeAllSessions();
4// Returns the number of sessions revoked

Checking Session Status

Check if a log entry represents an active session:

1$log = AuthenticationLog::find(1);
2 
3if ($log->isActive()) {
4 // Session is currently active
5}

Example: Session Management UI

Here's an example of how you might display active sessions to users:

1// In your controller
2public function sessions()
3{
4 $user = auth()->user();
5 $activeSessions = $user->getActiveSessions();
6 
7 return view('profile.sessions', compact('activeSessions'));
8}
9 
10// In your view
11@foreach($activeSessions as $session)
12 <div class="session-item">
13 <div>
14 <strong>{{ $session->device_name ?? 'Unknown Device' }}</strong>
15 @if($session->is_trusted)
16 <span class="badge badge-success">Trusted</span>
17 @endif
18 </div>
19 <div>
20 IP: {{ $session->ip_address }}
21 </div>
22 <div>
23 Last Login: {{ $session->login_at->diffForHumans() }}
24 </div>
25 <div>
26 <form action="{{ route('sessions.revoke', $session->id) }}" method="POST">
27 @csrf
28 @method('DELETE')
29 <button type="submit">Revoke Session</button>
30 </form>
31 </div>
32 </div>
33@endforeach

Example: Revoke Session Route

1Route::post('/sessions/{session}/revoke', function ($sessionId) {
2 $user = auth()->user();
3 
4 if ($user->revokeSession($sessionId)) {
5 return redirect()->back()->with('success', 'Session revoked successfully');
6 }
7 
8 return redirect()->back()->with('error', 'Failed to revoke session');
9})->name('sessions.revoke');