PHPackages                             syriable/laravel-user-context - 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. [Localization &amp; i18n](/categories/localization)
4. /
5. syriable/laravel-user-context

ActiveLibrary[Localization &amp; i18n](/categories/localization)

syriable/laravel-user-context
=============================

User presence, timezone awareness, locale context and login metadata for Laravel — know who is online, where they are, and what time it is for them.

1.0.3(1mo ago)06↓66.7%1MITPHPPHP ^8.3CI passing

Since Jul 18Pushed 1mo agoCompare

[ Source](https://github.com/syriable/laravel-user-context)[ Packagist](https://packagist.org/packages/syriable/laravel-user-context)[ Docs](https://github.com/syriable/laravel-user-context)[ GitHub Sponsors](https://github.com/syriable)[ RSS](/packages/syriable-laravel-user-context/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (4)Dependencies (40)Versions (5)Used By (1)

Laravel User Context
====================

[](#laravel-user-context)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a4ef5c49c41196ba3c057715474077135ddc7b1866769243023138f8ad4c1f68/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7379726961626c652f6c61726176656c2d757365722d636f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/syriable/laravel-user-context)[![GitHub Tests Action Status](https://camo.githubusercontent.com/bf704e965b50f13c05a5ef846f9acf45b88cb8249072f429bcafc3fa8e350b9d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7379726961626c652f6c61726176656c2d757365722d636f6e746578742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/syriable/laravel-user-context/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/c7885f05e25d4953a2742d3d433f51a6e3e15bafe24594125dd2ec0f55f55e57/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7379726961626c652f6c61726176656c2d757365722d636f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/syriable/laravel-user-context)

> Know who is **online**, **where** they are, and **what time it is for them** — presence, timezone awareness, locale context and login metadata for any Laravel app.

A lightweight, database-driven foundation package. No Redis, no heavy dependencies — presence works without a queue worker; geolocation lookups are queued by default so they never block the request path.

```
$user->isOnline();                       // true
$user->presence()->lastSeen();           // CarbonImmutable|null
$user->location()->countryName();        // "Sweden" (from ISO country code)
$user->timezone()->now();                // CarbonImmutable in the user's zone
$user->greeting();                       // "Good afternoon"

// A user in New York checking the best time to message a user in Shanghai:
$comparison = $newYorkUser->timeFor($shanghaiUser);
$comparison->formattedOffset();          // "+12:00"
$comparison->isNight();                  // true  → maybe wait
$comparison->isConvenientTime();         // false → not a good time to ping
```

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

[](#requirements)

- PHP 8.3+
- Laravel 11, 12 or 13

Installation
------------

[](#installation)

```
composer require syriable/laravel-user-context
```

Publish and run the migrations:

```
php artisan vendor:publish --tag="laravel-user-context-migrations"
php artisan migrate
```

Optionally publish the config file:

```
php artisan vendor:publish --tag="laravel-user-context-config"
```

Add the trait to your authenticatable model:

```
use Syriable\UserContext\Concerns\HasUserContext;

class User extends Authenticatable
{
    use HasUserContext;
}
```

Register the tracking middleware so activity is recorded on each request. In `bootstrap/app.php` (Laravel 11+):

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \Syriable\UserContext\Http\Middleware\TrackUserContext::class,
    ]);
})
```

That's it — logins, logouts, presence, locale and (optionally) geolocation are now tracked automatically.

Documentation
-------------

[](#documentation)

Publish the config (`php artisan vendor:publish --tag="laravel-user-context-config"`) and read the comments in `config/user-context.php` for every key. Notable defaults:

KeyDefaultWhy`ip.privacy``anonymize`Store `/24` (IPv4) / `/48` (IPv6) — not raw IPs`geolocation.driver``null`No external lookup until you opt into `ipinfo` / `maxmind` / `ipapi``queue.enabled``true`Geo lookups never block the request that recorded activity`routes.middleware``web, auth, throttle:60,1`Heartbeat is auth-gated and rate-limited```
use Syriable\UserContext\Facades\UserContext;

UserContext::isOnline($user);
UserContext::timezoneFor($user)->now();
UserContext::for($user); // ContextSnapshot
```

Usage at a glance
-----------------

[](#usage-at-a-glance)

### Presence

[](#presence)

```
$user->isOnline();                       // bool
$user->presence()->status();             // "online" | "offline"
$user->presence()->lastSeen();           // ?CarbonImmutable
$user->presence()->lastLogin();          // ?CarbonImmutable

UserContext::online()->count();          // query builder over online users
```

Keep a browser tab "online" with the bundled heartbeat component:

```

```

#### Presence source

[](#presence-source)

Laravel's `database` session driver already records `last_activity`, `ip_address` and `user_agent` for the authenticated user on every request. Rather than duplicate that, the package can read presence straight from Laravel's own `sessions` table. This is controlled by `presence.source`:

ValueBehavior`auto` (default)Read from `sessions` when the `database` session driver is active and the table exists; otherwise fall back to the package's own columns.`sessions`Always read from Laravel's `sessions` table (requires the `database` session driver).`table`Always read from the package's `user_contexts` columns — works on every session driver, supports polymorphic user models, and keeps the package's IP privacy modes.`auto` targets applications with a single authenticatable type. Presence reads (`isOnline()`, `presence()->lastSeen()`, `location()->ipAddress()`, `location()->userAgent()`) flow through the active source; login/logout timestamps, timezone, locale and geolocation always come from the package's own table, since Laravel's `sessions` table does not record them. The package still writes its own columns regardless of this setting, so switching sources never loses data.

Note

In `sessions` mode `location()->ipAddress()` returns the raw address Laravel stores on the session row; the `user-context.ip.privacy` modes (anonymize / hash / discard) apply only in `table` mode. Multi-guard or polymorphic setups should use the `table` source, because Laravel's `sessions.user_id` has no morph type.

### Timezone &amp; locale

[](#timezone--locale)

```
$user->timezone()->name();               // "Asia/Shanghai" (or null if unknown)
$user->localTime();                      // CarbonImmutable in their timezone
$user->isNight();                        // bool
$user->greeting();                       // localized "Good evening"
$user->locale();                         // "en_US"

// Explicit overrides always win over IP / header detection:
UserContext::overrideTimezone($user, 'Europe/Berlin');
UserContext::overrideLocale($user, 'de');
```

### Location

[](#location)

```
$user->location()->countryCode();        // "SE"
$user->location()->countryName();        // "Sweden"
$user->location()->city();               // "Stockholm"
$user->location()->ipAddress();          // last known IP (raw in sessions mode)
$user->location()->userAgent();          // last known User-Agent, or null
```

### User-to-user time comparison

[](#user-to-user-time-comparison)

```
$c = $userA->timeFor($userB);

$c->theirTime;            // CarbonImmutable in B's timezone
$c->formattedOffset();   // "+12:00"
$c->dayPeriod;           // DayPeriod::Night
$c->isConvenientTime();  // is it a reasonable local hour to contact B?

```

### Blade components

[](#blade-components)

```

```

### API

[](#api)

`GET /user-context/me` returns the authenticated user's context:

```
{
    "online": true,
    "last_seen": "2026-07-18T10:30:00+00:00",
    "timezone": "Europe/Stockholm",
    "local_time": "15:30",
    "country": "Sweden",
    "locale": "sv_SE"
}
```

Events
------

[](#events)

Listen for any of: `UserOnline`, `UserOffline`, `UserLocationUpdated`, `UserTimezoneChanged`, `UserLoginRecorded`. See [Extending](docs/extending.md).

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for what has changed recently.

Credits
-------

[](#credits)

- [syriable](https://github.com/syriable)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance91

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 71.4% 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

4

Last Release

45d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/286110444?v=4)[syriable](/maintainers/syriable)[@syriable](https://github.com/syriable)

---

Top Contributors

[![alkhatibsy](https://avatars.githubusercontent.com/u/23545455?v=4)](https://github.com/alkhatibsy "alkhatibsy (10 commits)")[![claude](https://avatars.githubusercontent.com/u/81847?v=4)](https://github.com/claude "claude (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laravelgeolocationlocaletimezoneonlinepresencelast-seensyriablelaravel-user-context

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/syriable-laravel-user-context/health.svg)

```
[![Health](https://phpackages.com/badges/syriable-laravel-user-context/health.svg)](https://phpackages.com/packages/syriable-laravel-user-context)
```

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.2k14.2M151](/packages/dedoc-scramble)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k6.1M53](/packages/spatie-laravel-pdf)[elegantly/laravel-translator

All on one translations management for Laravel

6547.8k](/packages/elegantly-laravel-translator)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

331634.0k38](/packages/codewithdennis-filament-select-tree)[askdkc/breezejp

Laravel Starter Kit (Livewire+Breeze+Laravel UI+Jetstream)や標準のバリデーションメッセージを全て一瞬で日本語化し、言語切替機能も提供するパッケージです / This package provides all-in-one Japanese translation for Laravel StarterKit (Livewire StarterKit, Breeze, Laravel UI and Jetstream) packages and validation messages with language switching feature.

592296.7k1](/packages/askdkc-breezejp)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

24795.1k](/packages/harris21-laravel-fuse)

PHPackages © 2026

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