Search code examples
phplaravel-10

How to set dynamic timezone in laravel


I have column timezone in my brands table.I want to make timezone dynamic such as which brand is there that time zone should be applied.

public function handle($request, Closure $next)
    {

        $user = Auth::user();

        $brandId = Auth::check() ? Auth::user()->brand : null;

        // Fetch the brand
        $brand = Brand::find($brandId); // You need to replace $brandId with the actual brand ID

        // Set the timezone
        if ($brand) {
            Config::set('app.timezone', $brand->timezone);
        } 
} 

I add this in my AdminAccess.php middleware but it is not storing exact timezone


Solution

  • Laravel News recently posted a tutorial related to your issue.

    Here's the link to it

    https://laravel-news.com/laravel-timezones

    You can create a Carbon::macro in the AppServiceProvider

    
    Carbon::macro('inBrandTimezone', function () {
        $timezone = auth()->user()?->brand?->timezone ?? config('app.timezone');
    
    
        return $this->tz($timezone);
    });
    

    Then you can use it in your app like:

    now()->inBrandTimezone()->format('Y-m-d')