Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sessions Devices Laravel Package

liberusoftware/sessions-devices

Laravel package for managing user sessions and devices: track active sessions, associate them with devices, and revoke access per session or device. Gives users control over where they're signed in and helps secure accounts with clear, auditable session oversight.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install and register

    composer require liberusoftware/sessions-devices
    

    In a Liberu modular app, enable the module through your module manager/modules_statuses.json; in a plain Laravel app, confirm the service provider is auto-discovered. Verify in composer.json / bootstrap/providers.php if discovery is disabled.

  2. Publish and migrate Check the package service provider for the exact publish tags, then run the equivalents of:

    php artisan vendor:publish --tag=sessions-devices-config
    php artisan vendor:publish --tag=sessions-devices-migrations
    php artisan migrate
    

    This package inventories active sessions, so you almost certainly need Laravel’s database session driver:

    php artisan session:table
    php artisan migrate
    

    Set SESSION_DRIVER=database in .env and clear config caches.

  3. Look here first

    • README.md and any docs/ folder for the public API.
    • src/Providers/*ServiceProvider.php for config keys, route registration, bindings, and publish tags.
    • config/sessions-devices.php (if published) for model, table, retention, and feature flags.
    • routes/ and src/Http/Controllers for the inventory and revocation endpoints.
    • database/migrations and src/Models for how sessions/devices are represented.
  4. First use case: “Active sessions” page Add a page for an authenticated user that lists their sessions/devices, flags the current one using session()->getId(), and offers “Revoke” for individual devices plus “Log out other sessions.” Protect the route with your normal auth middleware and resolve the user from the request, never from a request parameter.

Implementation Patterns

  • Inventory through the package, not raw queries. Prefer the package’s repository/service or model scope over hand-written DB::table('sessions') queries. If it exposes a DTO/resource, use that so device labels, “last active,” IP handling, and the current-session flag stay consistent across web and API responses.

  • Scope everything to the authenticated user. A typical controller flow:

    $sessions = $this->sessions->forUser($request->user());
    // or: $request->user()->sessions()->latest('last_activity')->get();
    
    return view('sessions.index', [
        'sessions' => $sessions,
        'currentSessionId' => $request->session()->getId(),
    ]);
    

    For APIs/SPAs, return the same inventory as JSON with an is_current boolean. Do not expose raw IP addresses or full user agents to roles that don’t need them.

  • Current-session protection belongs in policy + UI + endpoint. Compare the target session ID to session()->getId() in the revocation handler and return 403/validation error if equal. Disable the revoke button for the current row. This avoids the confusing “revoke yourself and get logged out” behavior.

  • Revocation workflows. Support the three common actions explicitly:

    • Revoke one session/device (delete/invalidate that session record).
    • Revoke all other sessions (the common “I lost my phone” action).
    • Revoke all sessions, including current, then redirect to login. Use POST/DELETE with CSRF, a confirmation modal, and a consistent redirect back with a status message. Wrap multi-row revocations in a transaction if the package fires events or writes audit rows.
  • Decide between row deletion and Laravel’s password-based invalidation. Laravel’s logoutOtherDevices($password) re-hashes the password and invalidates other sessions through the auth guard; deleting session rows is more direct but bypasses that mechanism. Pick one approach per flow and document it, because mixing them produces inconsistent “still logged in on another device” reports.

  • Middleware for device limits and stale-session cleanup. A login-time middleware can enforce a maximum device count or revoke sessions older than N days. Register it after StartSession and after authentication, otherwise session()->getId() and $request->user() are unavailable. Keep the middleware small and delegate the actual revocation to the package service.

  • Authorization policy. Add a SessionPolicy/DevicePolicy with view and revoke methods that verify ownership. This is especially important if session IDs appear in URLs or Livewire component actions.

  • Events and notifications for day-to-day operations. Listen for the package’s revocation/new-session events (if provided) to write audit logs or send “new device signed in” notifications. If events aren’t available, dispatch your own from the controller after successful revocation.

  • Retention and privacy. Schedule the package’s cleanup command if it provides one; otherwise prune old sessions rows and any device metadata on a schedule. Hash or truncate IP/user-agent data if the package config allows it, and document retention in your privacy policy.

  • Testing pattern. Use actingAs($user), withSession([...]), and database assertions against the sessions table. For “current session” behavior, freeze time and assert that revoking another session leaves the current row intact while revoking the current session logs the user out on the next request.

Gotchas and Tips

  • Database driver dependency. With SESSION_DRIVER=redis, file, or cookie, there may be no per-session rows to inventory. The package can only reliably list sessions when the database driver (or equivalent persistent store) is used. Check this before debugging “empty session list” reports.

  • Session ID regeneration. Laravel regenerates the session ID on login and privilege changes. Always read session()->getId() at request time; don’t cache it in a service provider or compare against a value stored earlier in the request lifecycle.

  • Revoking the current session logs the user out immediately. That’s expected, but it surprises users and testers. Guard the endpoint and make the UI explicit (“This will sign you out”).

  • user_id can be null in the sessions table. Rows may exist before authentication or after logout. Filter by the authenticated user and don’t assume every row maps to a device you can attribute.

  • Proxy and IP correctness. Behind a load balancer, raw REMOTE_ADDR is the proxy. Configure TrustProxies correctly before relying on IP-based device labels or security decisions.

  • Multi-guard applications. Sessions are tied to the guard/user provider that created them. If you have admin and customer guards, verify the package scopes correctly; don’t let an admin inventory bleed into customer sessions.

  • Config and route caching. After publishing config or changing routes, run php artisan config:clear and php artisan route:clear. Modular apps are especially prone to stale cached config after enabling a module.

  • Migration conflicts in modular installs. If the package’s migration alters or duplicates Laravel’s sessions table, publish it and adjust timestamps/names rather than editing vendor files. Always run migrations on a fresh test database before production.

  • Low-maturity dependency risk. With zero stars/dependents and a very recent release, pin an exact version in composer.json, read the service provider and revocation code before trusting it, and add your own feature tests around the flows you depend on. Treat the published release tag as the source of truth and verify it matches the repository state.

  • Debugging checklist for “session not revoked”: confirm the session driver is database; confirm the target row exists and belongs to the user; confirm the middleware order includes StartSession and auth; confirm the request is not hitting a cached route; log the session ID being revoked and compare with session()->getId().

  • Extension points to prefer: config-driven model/service bindings, published views/components, package events, and a custom repository binding. Avoid subclassing controllers or copying package code into your app, since updates will be harder to apply.

  • Privacy defaults. Active-session screens often expose IP addresses and device fingerprints. Gate that detail behind a permission, mask/truncate it for regular users, and make sure revocation audit logs follow the same retention rules as the sessions themselves.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource