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

Filament Browser Timezone Laravel Package

webteractive/filament-browser-timezone

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webteractive/filament-browser-timezone
    

    No additional configuration is required for basic usage.

  2. First Use Case: Access the browser timezone in a Filament resource:

    use Webteractive\FilamentBrowserTimezone\BrowserTimezone;
    
    // In a Resource, Form, or Widget
    $timezone = BrowserTimezone::get(); // Returns 'America/New_York' or fallback
    
  3. Where to Look First:

    • Helper Class: BrowserTimezone facade (automatically available)
    • Configuration: config/filament-browser-timezone.php (published via php artisan vendor:publish --tag="filament-browser-timezone-config")
    • Livewire Component: Automatically injected via Filament render hooks

Implementation Patterns

Core Workflows

1. Timezone-Aware Filament Tables

use Webteractive\FilamentBrowserTimezone\BrowserTimezone;

class UserResource extends Resource {
    public function table(Table $table): Table {
        return $table->columns([
            TextColumn::make('created_at')
                ->dateTime()
                ->timezone(BrowserTimezone::get()) // Dynamic timezone
                ->label('Created At'),
        ]);
    }
}

2. User-Specific Timezone Handling

// Override browser timezone for specific users (e.g., admins)
if (auth()->user()->is_admin) {
    $timezone = 'UTC';
} else {
    $timezone = BrowserTimezone::get('UTC'); // Fallback to UTC
}

3. Dynamic Form Fields

use Webteractive\FilamentBrowserTimezone\BrowserTimezone;

class EventForm extends Form {
    public function form(Form $form): Form {
        return $form->schema([
            DateTimePicker::make('event_time')
                ->timezone(BrowserTimezone::get())
                ->label('Event Time'),
        ]);
    }
}

4. Widget Data Filtering

use Webteractive\FilamentBrowserTimezone\BrowserTimezone;

class RecentActivityWidget extends Widget {
    protected function getTableQuery(): Builder {
        return Activity::query()
            ->where('created_at', '>=', now()->setTimezone(BrowserTimezone::get()))
            ->latest();
    }
}

Integration Tips

1. Conditional Timezone Logic

if (BrowserTimezone::has()) {
    $timezone = BrowserTimezone::get();
} else {
    // Fallback logic (e.g., user preference or default)
    $timezone = auth()->user()->timezone ?? config('app.timezone');
}

2. Debugging Timezone Issues

Enable debug mode in config/filament-browser-timezone.php:

'debug' => env('APP_ENV') === 'local',

Logs timezone detection attempts to Laravel logs.

3. Testing Timezone Scenarios

// In PHPUnit/Pest tests
BrowserTimezone::resetState(); // Clear cached state
BrowserTimezone::setForTesting('Europe/London'); // Mock timezone

4. Session Management

Clear timezone data manually:

php artisan filament:timezone:clear

Or programmatically:

BrowserTimezone::clear();

Gotchas and Tips

Pitfalls

  1. Browser Compatibility:

    • Older browsers (pre-Chrome 24, Firefox 29, Safari 10) will silently fall back to the configured fallback_timezone.
    • Test in IE11 or legacy browsers if supporting them.
  2. Session Key Conflicts:

    • Ensure session_key in config doesn’t clash with existing session keys.
    • Default: 'browser_timezone'.
  3. Livewire Component Injection:

    • The package uses Filament’s render hooks (panels::body.start). If hooks are disabled or overridden, timezone detection may fail.
    • Fix: Verify your Filament panel’s register method includes:
      Panel::make()->hooks([
          RenderHook::make('panels.body.start')
              ->view('filament-browser-timezone::timezone-sync'),
      ]);
      
  4. Timezone Validation:

    • Invalid timezones (e.g., 'Invalid/Zone') are rejected since v1.5.2. Use BrowserTimezone::isValid('Europe/London') to validate manually.
  5. Caching Interference:

    • If using Laravel’s cache, ensure BrowserTimezone::get() isn’t cached globally (it reads from the session).

Debugging Tips

  1. Check Session Data:

    dd(session()->get('browser_timezone')); // Debug stored value
    
  2. Validate JavaScript Detection:

    • Open browser dev tools (F12) and check the Network tab for livewire requests containing timezone data.
    • Look for errors in the Console tab (e.g., Intl.DateTimeFormat unsupported).
  3. Log Timezone Detection: Enable debug mode and check storage/logs/laravel.log for:

    [BrowserTimezone] Detected: America/New_York
    [BrowserTimezone] Fallback used: UTC
    
  4. Clear Stale Data:

    • If timezones appear stale, clear the session or run:
      php artisan filament:timezone:clear
      

Extension Points

  1. Custom Timezone Logic: Override the default detection by publishing the Livewire component:

    php artisan vendor:publish --tag="filament-browser-timezone-views"
    

    Modify resources/views/vendor/filament-browser-timezone/timezone-sync.blade.php.

  2. Add Timezone to User Model: Sync browser timezone to the user model:

    use Webteractive\FilamentBrowserTimezone\BrowserTimezone;
    
    auth()->user()->update(['timezone' => BrowserTimezone::get()]);
    
  3. Multi-Tenancy Support: Store timezone per tenant:

    session()->put('tenant_' . tenant()->id . '_timezone', BrowserTimezone::get());
    
  4. Fallback Hierarchy: Extend the fallback logic in BrowserTimezone::get():

    $timezone = BrowserTimezone::get() ?: auth()->user()->timezone ?: config('app.timezone');
    

Performance Optimizations

  1. Avoid Redundant Calls: Cache the timezone in a property if used repeatedly:

    private $userTimezone;
    
    public function getUserTimezone() {
        return $this->userTimezone ??= BrowserTimezone::get();
    }
    
  2. Lazy-Load Timezone: Defer timezone resolution until needed:

    $timezone = fn() => BrowserTimezone::get();
    
  3. Disable for Non-Interactive Requests: Skip detection for APIs or CLI:

    if (!app()->runningInConsole() && !request()->wantsJson()) {
        $timezone = BrowserTimezone::get();
    }
    

Config Quirks

  1. Fallback Timezone Validation: Since v1.5.2, invalid fallback_timezone values default to 'UTC'. Validate with:

    if (!BrowserTimezone::isValid(config('filament-browser-timezone.fallback_timezone'))) {
        config(['filament-browser-timezone.fallback_timezone' => 'UTC']);
    }
    
  2. Session Driver: Ensure your session driver (e.g., file, database, redis) is properly configured. Timezone data won’t persist if sessions fail.

  3. Livewire Version Conflicts: The package supports Livewire v3/v4. If you encounter issues, pin the Livewire version in composer.json:

    "require": {
        "livewire/livewire": "^3.0||^4.0"
    }
    

Testing Support

  1. Mock Timezone in Tests:

    // Pest/PHPUnit
    BrowserTimezone::setForTesting('Asia/Tokyo');
    $this->assertEquals('Asia/Tokyo', BrowserTimezone::get());
    
  2. Reset State:

    BrowserTimezone::resetState(); // Clears cached session data
    
  3. Test Fallback:

    // Simulate missing session data
    session()->forget('browser_timezone');
    $this->assertEquals('UTC', BrowserTimezone::get('UTC'));
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity