PHPackages                             jftecnologia/laravel-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. jftecnologia/laravel-context

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jftecnologia/laravel-context
============================

Context on steroids for Laravel applications

v1.0.2(3mo ago)0660↓50%21MITPHPPHP ^8.4CI passing

Since Feb 12Pushed 3mo agoCompare

[ Source](https://github.com/jftecnologia/laravel-context)[ Packagist](https://packagist.org/packages/jftecnologia/laravel-context)[ Docs](https://github.com/jftecnologia/laravel-context)[ RSS](/packages/jftecnologia-laravel-context/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (8)Versions (4)Used By (1)

Laravel Context
===============

[](#laravel-context)

[![Latest Version on Packagist](https://camo.githubusercontent.com/102aa23ded81617e822ebed62d8f33c3309cfbc678299e65f83c2231e95d3bf9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a667465636e6f6c6f6769612f6c61726176656c2d636f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jftecnologia/laravel-context)[![GitHub Tests Action Status](https://camo.githubusercontent.com/7bd83539350babdeae5d0db6a4bbae403cd82425cec9ab7c0a721cbc694b128f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a667465636e6f6c6f6769612f6c61726176656c2d636f6e746578742f74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/jftecnologia/laravel-context/actions?query=workflow%3Atests+branch%3Amaster)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/c8d5d46c6ac80faa602d73ea94311ad5decaaa4cfc61907887058a2903c6a0f6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a667465636e6f6c6f6769612f6c61726176656c2d636f6e746578742f6669782d7068702d636f64652d7374796c652e796d6c3f6272616e63683d6d6173746572266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/jftecnologia/laravel-context/actions?query=workflow%3A%22fix-php-code-style-issues%22+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/1929b8de13599b8ad8b7b7b11f01f3e058361d1c3d61febc91763b9e1f8264ea/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a667465636e6f6c6f6769612f6c61726176656c2d636f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jftecnologia/laravel-context)

A powerful and extensible package for managing application context in Laravel. Automatically collect and distribute context information from multiple sources (user, request, environment, etc.) to various channels (logs, monitoring systems, etc.).

Features
--------

[](#features)

- **Automatic Context Collection**: Built-in providers for timestamp, app info, host info, request data, and user information
- **Smart Caching**: Intelligent per-provider caching - static context is cached for performance, dynamic context (user, request) is always fresh
- **Extensible Architecture**: Easy to create custom providers and channels
- **Conditional Execution**: Providers can determine when they should run
- **Multiple Channels**: Register context in different systems (logs, monitoring, etc.)
- **Facade Support**: Clean and elegant API using Laravel facades
- **Configuration-Based**: Manage providers and channels through a simple config file
- **Performance Optimized**: Selective caching ensures optimal performance without stale data

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

[](#installation)

You can install the package via composer:

```
composer require jftecnologia/laravel-context
```

The package will automatically register its service provider.

Configuration
-------------

[](#configuration)

Publish the configuration file:

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

This will create a `config/laravel-context.php` file with the following structure:

```
return [
    'enabled' => env('LARAVEL_CONTEXT_ENABLED', true),

    'providers' => [
        // Built-in providers
        JuniorFontenele\LaravelContext\Providers\TimestampProvider::class,
        JuniorFontenele\LaravelContext\Providers\AppProvider::class,
        JuniorFontenele\LaravelContext\Providers\HostProvider::class,
        JuniorFontenele\LaravelContext\Providers\RequestProvider::class,
        JuniorFontenele\LaravelContext\Providers\UserProvider::class,
    ],

    'channels' => [
        JuniorFontenele\LaravelContext\Channels\LogChannel::class,

        // Add your custom channels here
    ],
];
```

Basic Usage
-----------

[](#basic-usage)

### Using the Facade

[](#using-the-facade)

```
use JuniorFontenele\LaravelContext\Facades\LaravelContext;

// Build the context (optional, will be built automatically on first access)
LaravelContext::build();

// Get all context
$context = LaravelContext::all();

// Get a specific context value
$userId = LaravelContext::get('user.id');
$appName = LaravelContext::get('app.name');

// Get with a default value
$userName = LaravelContext::get('user.name', 'Guest');

// Check if a key exists
if (LaravelContext::has('user.id')) {
    // User is authenticated
}

// Set a custom value and immediately notify registered channels
LaravelContext::set('custom.key', 'custom value');

// Rebuild context from scratch (clears all caches and rebuilds)
LaravelContext::rebuild();

// Clear cache for a specific provider
use JuniorFontenele\LaravelContext\Providers\TimestampProvider;
LaravelContext::clearProviderCache(TimestampProvider::class);

// Clear the context (clear now also notifies channels with empty context)
LaravelContext::clear();

// Note: `LaravelContext::build()` now short-circuits after the first execution and simply replays the cached context to the channels. Call `clear()` or `rebuild()` to force a fresh collection, and use `sendContextToChannels()` whenever you want to resync the channels without rerunning the providers.
```

### Context Structure

[](#context-structure)

The default context includes:

```
[
    'timestamp' => '2024-01-21T10:30:00+00:00',
    'app' => [
        'name' => 'Laravel',
        'env' => 'production',
        'debug' => false,
        'url' => 'https://example.com',
        'timezone' => 'UTC',
        'locale' => 'en',
        'origin' => 'web', // or 'console'
    ],
    'host' => [
        'name' => 'server-01',
        'ip' => '192.168.1.100',
    ],
    'request' => [ // Only available in web requests
        'ip' => '192.168.1.1',
        'method' => 'GET',
        'url' => 'https://example.com/api/users',
        'host' => 'example.com',
        'scheme' => 'https',
        'locale' => 'en',
        'referer' => 'https://example.com',
        'user_agent' => 'Mozilla/5.0...',
        'accept_language' => 'en-US,en;q=0.9',
    ],
    'user' => [ // Only when authenticated (always up-to-date)
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ],
]
```

> **Note**: User, request and timestamp contexts are **always fresh** and automatically updated when authentication state or request data changes. Static contexts (app, host) are cached for optimal performance.

Smart Caching System
--------------------

[](#smart-caching-system)

The package uses an intelligent per-provider caching system:

### Cacheable Providers (Static Context)

[](#cacheable-providers-static-context)

Providers that return static data are cached for optimal performance:

- `AppProvider` - Application configuration doesn't change
- `HostProvider` - Host information is static

These providers execute **once per request** and their results are cached.

### Dynamic Providers (Always Fresh)

[](#dynamic-providers-always-fresh)

Providers with dynamic data are **never cached** and always recalculated:

- `TimestampProvider` - Timestamp can change during request lifecycle
- `UserProvider` - Authentication state can change (login/logout)
- `RequestProvider` - Request data can be modified by middlewares

These providers execute **every time** you access the context, ensuring data is always up-to-date.

### Example: Login/Logout Scenario

[](#example-loginlogout-scenario)

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

// Before login
$context = LaravelContext::all();
// Result: no 'user' key (not authenticated)

// User logs in
Auth::login($user);

// After login - NO need to call refresh()!
$context = LaravelContext::all();
// Result: 'user' key is present with fresh data
// 'app' and 'host' are from cache (fast!)
```

No manual cache management needed! The context stays fresh where it matters while maintaining optimal performance.

Creating Custom Providers
-------------------------

[](#creating-custom-providers)

Providers are classes that collect specific context information. Create a custom provider by implementing the `ContextProvider` interface or extending `AbstractProvider`:

### Basic Provider (Cacheable)

[](#basic-provider-cacheable)

```
