Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change TimeZone dynamically in laravel

In my project there is drop-down of time zones(PT,CST etc), when Admin changes the timezone from drop-down the admin panel reflects the timezone from the selected drop down.
How to change Config/app.php "timezone"( Application Timezone) according to the selected option.

like image 500
SVM Avatar asked Dec 22 '17 08:12

SVM


4 Answers

you need also call date_default_timezone_set

    config(['app.timezone' => $timezone]);
    date_default_timezone_set($timezone);
like image 94
the_hasanov Avatar answered Nov 04 '22 22:11

the_hasanov


You can use Laravel helper function config to set timezone. However, this will affects only the request you will receive.

config(['app.timezone' => $timezone]);

If your goal is to change once the timezone and run on every request then what about saving the changed timezone in DB or in a file. Then, write a query for DB or read a file in app/config.php and change the value of index timezone in a file.

For example (file example):

When you changed the timezone it saves in a file.

file_put_contents("path/to/file", $timezone);

And, in app/config.php

$timezone= file_get_contents("path/to/file");
return [
 . . .   
    'timezone' => $timezone,
 . . .
]
like image 29
Phoenix404 Avatar answered Nov 04 '22 21:11

Phoenix404


If you want to keep a new time zone for all future requests, you need to use a package like larapack/config-writer to be able to save the time zone to the app config file.

Another way to handle this is to keep time zone in DB, fetch it in every request and set it with config(['app.timezone' => $timezone]) dynamically.

like image 3
Alexey Mezenin Avatar answered Nov 04 '22 21:11

Alexey Mezenin


You can use middleware to achieve this, whichever routes you will write mention all those applying with that middleware.
You can fetch that data from database and apply it like as follows,

config('app.timezone', 'your selected timezone')
like image 2
Rahul Avatar answered Nov 04 '22 23:11

Rahul