Weave Code
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

Context Laravel Laravel Package

bonnier/context-laravel

Laravel service provider and middleware for registering a request context. Install via Composer, add the ContextServiceProvider in config/app.php, and enable the RegisterContext middleware in Http/Kernel.php to make context available across your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bonnier/context-laravel
    

    Publish the config file:

    php artisan vendor:publish --provider="Bonnier\Context\ContextServiceProvider"
    
  2. Configuration Edit config/context.php to define your context keys (e.g., locale, country, theme):

    'keys' => [
        'locale' => 'en',
        'country' => 'us',
        'theme' => 'light',
    ],
    
  3. First Use Case Inject the Context facade into a controller or service:

    use Bonnier\Context\Facades\Context;
    
    public function index()
    {
        // Set a context value
        Context::set('locale', 'sv');
    
        // Get a context value
        $locale = Context::get('locale');
    
        // Check if a context exists
        if (Context::has('theme')) {
            // ...
        }
    }
    
  4. Middleware Integration Use the ContextMiddleware to set context values from request data (e.g., URL parameters or headers):

    Route::get('/{locale}', function ($locale) {
        // ...
    })->middleware('context');
    

    Configure middleware in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \Bonnier\Context\Middleware\ContextMiddleware::class,
    ];
    

Implementation Patterns

Core Workflows

  1. Dynamic Context Resolution Override default values based on request context (e.g., locale from subdomain):

    public function handle($request, Closure $next)
    {
        $locale = $request->getHost(); // e.g., "sv.example.com"
        Context::set('locale', str_replace('.', '', $locale));
    
        return $next($request);
    }
    
  2. Context-Aware Views Pass context to Blade templates:

    return view('welcome', [
        'context' => Context::all(),
    ]);
    

    In Blade:

    <html lang="{{ $context['locale'] }}">
    
  3. Service Provider Binding Bind context-dependent services in AppServiceProvider:

    public function boot()
    {
        $this->app->bind(
            \App\Services\LocalizationService::class,
            function ($app) {
                return new \App\Services\LocalizationService(
                    Context::get('locale')
                );
            }
        );
    }
    
  4. Fallback Logic Use Context::get('key', 'fallback') to handle missing keys gracefully:

    $country = Context::get('country', 'us');
    

Integration Tips

  • APIs: Set context from API headers (e.g., X-Locale):
    Context::set('locale', $request->header('X-Locale'));
    
  • Testing: Mock context in tests:
    Context::shouldReceive('get')->with('locale')->andReturn('test');
    
  • Caching: Cache context-aware responses:
    $cacheKey = 'user_'.Context::get('locale').'_data';
    

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters Ensure ContextMiddleware runs before other middleware that relies on context (e.g., localization). Add it early in $middleware or $middlewareGroups.

  2. Config Overrides Default values in config/context.php are not merged with runtime values. Explicitly set keys in middleware or controllers:

    // ❌ Won't override config
    Context::set('locale', 'sv'); // If 'locale' is already 'en' in config
    
    // ✅ Correct: Override explicitly
    Context::set('locale', 'sv', true); // Force override (if method supports it)
    

    Note: The package may not support forced overrides; check the source.

  3. Thread Safety Context is likely not thread-safe. Avoid setting context in queues or background jobs unless explicitly designed for it.

  4. Deprecated Methods The package is outdated (last release: 2020). Assume undocumented methods may break. Prefer get(), set(), and has().

Debugging

  • Log Context Add a temporary middleware to log context:
    public function handle($request, Closure $next)
    {
        \Log::debug('Current context:', Context::all());
        return $next($request);
    }
    
  • Check for Typos Context keys are case-sensitive. Debug with:
    \Log::debug('Available keys:', array_keys(Context::all()));
    

Extension Points

  1. Custom Context Sources Extend ContextMiddleware to add new sources (e.g., database):

    public function handle($request, Closure $next)
    {
        $userContext = UserContext::resolve($request->user());
        Context::merge($userContext);
    
        return $next($request);
    }
    
  2. Event-Based Context Trigger events when context changes (e.g., ContextUpdated):

    Context::set('locale', 'sv');
    event(new \App\Events\ContextUpdated('locale', 'sv'));
    
  3. Override Facade Replace the facade for custom logic:

    Facades\Context::swap(new \App\Services\CustomContext);
    

Performance

  • Avoid Heavy Logic in Middleware Context middleware runs on every request. Offload expensive operations (e.g., DB calls) to controllers or services.
  • Cache Context For static contexts (e.g., theme), cache values:
    $theme = Cache::remember("context.theme", 3600, function() {
        return Context::get('theme');
    });
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours