PHPackages                             willvincent/laravel-session-manager - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. willvincent/laravel-session-manager

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

willvincent/laravel-session-manager
===================================

Enhanced session management for Laravel with device tracking and remote logout

1.1.0(5mo ago)0235MITPHPPHP ^8.2CI passing

Since Dec 14Pushed 5mo agoCompare

[ Source](https://github.com/willvincent/laravel-session-manager)[ Packagist](https://packagist.org/packages/willvincent/laravel-session-manager)[ GitHub Sponsors](https://github.com/willvincent)[ Fund](https://thanks.dev/gh/willvincent)[ RSS](/packages/willvincent-laravel-session-manager/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (11)Versions (4)Used By (0)

Laravel Session Manager
=======================

[](#laravel-session-manager)

Enhanced session management for Laravel applications with device tracking and remote session termination.

[![Tests](https://github.com/willvincent/laravel-session-manager/actions/workflows/tests.yml/badge.svg)](https://github.com/willvincent/laravel-session-manager/actions/workflows/tests.yml)[![codecov](https://camo.githubusercontent.com/01eeb56506d721e2376a9cade785a6d9ae6d520eea1d9a1f75d3edeab158d0eb/68747470733a2f2f636f6465636f762e696f2f67682f77696c6c76696e63656e742f6c61726176656c2d73657373696f6e2d6d616e616765722f67726170682f62616467652e7376673f746f6b656e3d3541555148454a575a36)](https://codecov.io/gh/willvincent/laravel-session-manager)

Features
--------

[](#features)

- 📱 Track user sessions across devices
- 🔒 Remote logout from other devices
- 🚀 Works with any session driver (database, redis, file, etc.)
- ⚡ Optimized with throttling and indexing
- 🧪 Fully tested (100% test and type coverage &amp; PHPStan Level 9)

---

Quick Start
-----------

[](#quick-start)

#### Install the package

[](#install-the-package)

```
composer require willvincent/laravel-session-manager
```

#### Publish config and language files

[](#publish-config-and-language-files)

```
php artisan vendor:publish --tag=session-manager-config
php artisan vendor:publish --tag=session-manager-lang
```

### If **not** using the `database` session driver

[](#if-not-using-the-database-session-driver)

> The following steps are **only required** if your application is **not** using Laravel’s `database` session driver.

#### Publish migrations and ensure the sessions table exists

[](#publish-migrations-and-ensure-the-sessions-table-exists)

```
php artisan vendor:publish --tag=session-manager-migrations
php artisan session:table   # Only if the sessions table does not already exist
php artisan migrate
```

#### Register the session indexing middleware

[](#register-the-session-indexing-middleware)

Add the middleware to the `web` middleware group:

```
// bootstrap/app.php

->withMiddleware(function (Middleware $middleware): void {
    $middleware->web(append: [
        \WillVincent\SessionManager\Http\Middleware\IndexSessionMetadata::class,
    ]);
})
```

#### Schedule pruning of stale session data

[](#schedule-pruning-of-stale-session-data)

```
// routes/console.php

use Illuminate\Support\Facades\Schedule;

Schedule::command('session-manager:prune-sessions')
    ->daily();
```

Adjust the schedule as needed. By default, the command removes session records older than Laravel’s configured session lifetime.

Optional flags:

- `--ttl=MINUTES` — override the session lifetime
- `--dry-run` — show how many records would be deleted without deleting them

Example:

```
php artisan session-manager:prune-sessions --dry-run
```

### Using the `database` session driver?

[](#using-the-database-session-driver)

If your application **uses Laravel’s `database` session driver**, the steps above are **not required**.

In this case:

- Session metadata is read directly from Laravel’s `sessions` table
- Session records are already created and maintained automatically
- Laravel’s built-in session garbage collection handles expiration

### ✅ That’s it

[](#-thats-it)

Session metadata will now be tracked automatically and kept clean over time.

---

### Using the Facade

[](#using-the-facade)

The package exposes a **facade-first API**, consistent with Laravel’s native style:

```
use WillVincent\SessionManager\Facades\SessionManager;
```

Fetch all sessions for the authenticated user:

```
$sessions = SessionManager::getUserSessions(auth()->id());
```

Log out all other sessions (after password confirmation):

```
SessionManager::logoutOtherSessions(auth()->id());
```

---

Comparison with Laravel’s Built-in Session Logout
-------------------------------------------------

[](#comparison-with-laravels-built-in-session-logout)

Laravel provides:

```
Auth::logoutOtherDevices($password);
```

**Limitations of the built-in approach:**

- ❌ No built-in API/UI to list sessions or devices in Laravel core (except in some starter kits)
- ❌ No or limited session metadata (IP, browser, device, location)
- ❌ Not session-aware or targetable (all-or-nothing)
- ❌ Depends on `AuthenticateSession` middleware

**Laravel Session Manager:**

- ✅ Works with **all** native session drivers (Redis, database, file, etc.)
- ✅ Lists all active sessions and devices
- ✅ Allows targeted or bulk remote logout
- ✅ Optional [IP-based location enrichment](LOCATION.md)

If you need visibility and control beyond a blind logout call, this package fills the gap.

---

Usage
-----

[](#usage)

### Get User Sessions

[](#get-user-sessions)

```
use WillVincent\SessionManager\Facades\SessionManager;

$sessions = SessionManager::getUserSessions(auth()->id());

foreach ($sessions as $session) {
    echo $session->agent->platform();   // e.g. "macOS"
    echo $session->agent->browser();    // e.g. "Chrome"
    echo $session->ip_address;          // e.g. "192.168.1.1"
    echo $session->is_current_device;   // true / false
    echo $session->last_active;         // "2 minutes ago"

    // Optional location data
    echo $session->location?->labelWithConfidence(include_country: true);
}
```

### Logout Other Sessions

[](#logout-other-sessions)

```
use WillVincent\SessionManager\Facades\SessionManager;

$request->validate([
    'password' => ['required', 'current_password'],
]);

SessionManager::logoutOtherSessions(auth()->id());
```

---

Livewire Example
----------------

[](#livewire-example)

```
use Livewire\Component;
use WillVincent\SessionManager\Facades\SessionManager;

class SessionSettings extends Component
{
    public string $password = '';

    public function getSessionsProperty()
    {
        return SessionManager::getUserSessions(auth()->id());
    }

    public function logoutOtherSessions()
    {
        $this->validate([
            'password' => ['required', 'current_password'],
        ]);

        SessionManager::logoutOtherSessions(auth()->id());

        $this->dispatch('sessions-updated');
    }

    public function render()
    {
        return view('livewire.session-settings');
    }
}
```

---

Advanced: Service Container Access
----------------------------------

[](#advanced-service-container-access)

Most applications should use the facade. If you prefer constructor injection:

```
use WillVincent\SessionManager\SessionManager;

public function __construct(
    private SessionManager $sessions,
) {}

$this->sessions->logoutOtherSessions($userId);
```

---

Session Driver Support
----------------------

[](#session-driver-support)

The ability to list and remotely terminate sessions depends on the underlying session driver.

Session DriverList user sessionsLog out other sessions`database`✅✅`redis`✅✅`file`✅✅`cookie`✅❌`array`❌❌### Cookie Session Driver Notes

[](#cookie-session-driver-notes)

When using the `cookie` session driver, session data is stored entirely client-side. Because there is no server-side session store, **remote session termination is not possible** via this package alone.

If your application uses cookie-based sessions and you want to invalidate other devices, you **must also** call Laravel’s built-in method:

```
use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices($password);
```

This requires validating the user’s password (which you should already be doing before calling `logoutOtherSessions`). Laravel will then invalidate authentication on other devices on their next request via the `AuthenticateSession` middleware.

In this scenario, this package will still:

- Track session metadata
- Clean up stored session records

…but Laravel handles the actual authentication invalidation.

### Array Session Driver Notes

[](#array-session-driver-notes)

The `array` session driver stores session data **in memory for the current request only**. Sessions do not persist across requests, processes, or devices.

Because of this:

- Sessions cannot be listed
- Sessions cannot be remotely terminated
- Session metadata has no meaningful lifespan

The `array` driver is intended for testing and local development only and is not compatible with multi-device session management.

---

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11.0+
- Default Laravel session table (create via `php artisan session:table`)
- doctrine/dbal (installs with this package, required for altering the sessions table)
- `geoip2/geoip2`, `symfony/intl`, and `ext-intl` are optional (for IP location support)

---

License
-------

[](#license)

This package is [MIT](LICENSE.md) licensed, and free to use, fork, etc.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance72

Regular maintenance activity

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

155d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0c6239b14bdb77aba00cd0bc65f561ad8dd694ec4a18508c69eff119352d54fa?d=identicon)[willvincent](/maintainers/willvincent)

---

Top Contributors

[![willvincent](https://avatars.githubusercontent.com/u/689891?v=4)](https://github.com/willvincent "willvincent (23 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/willvincent-laravel-session-manager/health.svg)

```
[![Health](https://phpackages.com/badges/willvincent-laravel-session-manager/health.svg)](https://phpackages.com/packages/willvincent-laravel-session-manager)
```

###  Alternatives

[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)[truckersmp/steam-socialite

Laravel Socialite provider for Steam OpenID.

1516.7k](/packages/truckersmp-steam-socialite)[pschocke/laravel-telegram-login-widget

Easily integrate Telegrams login widget into your Laravel application to send Telegram messages

1610.4k](/packages/pschocke-laravel-telegram-login-widget)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
