Vince Carter
Vince Carter

Reputation: 946

Laravel set dynamically timezone for one Controller

i am developing website on Laravel. I set the default timezone in the config/app.php, but i have one section where the information there must be shown regarding the user timezone. Is there an option for one specific controller to use the user timezone ?

Upvotes: 1

Views: 4537

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

If you want to show local time for every user and you use Laravel dates (Carbon), you can do something like this:

if (Auth::check()) {
    $object->created_at->setTimezone(Auth::user->timezone)
}

Upvotes: 0

patricus
patricus

Reputation: 62338

You can use the config() helper to set config values at any point in your request. This change affects that request only.

So, in your case, one option would be to update the config setting inside the constructor to your controller. Then, any requests that are handled by that controller will use the updated timezone setting.

class MyController extends Controller
{
    public function __construct()
    {
        config(['app.timezone' => 'America/Chicago']);
    }
}

You can move that statement pretty much anywhere as more global or granular control is needed.

Upvotes: 3

Related Questions