How to change the timezone dynamically in laravel
Apr 2, 2022
How to change the timezone dynamically in laravel?
You can use laravel helper function config of the set timezone.
How do we set timezone in laravel?
First of all, we open AppServiceProvider.php. We will write code in the boot section.
First, we check our table already have on the database. Otherwise, we will get on errors when migrating.
if (Schema::hasTable('settings')) {
// statement
}
Fetch the timezone name from the database
if (Schema::hasTable('settings')) {
$timeZone = Setting::select('timezone')->first();
}
After fetched the timezone, we set the timezone in the config array
config(['app.timezone' => $timeZone->timezone]);
date_default_timezone_set($timeZone->timezone);
That’s it.
Full code
Let’s go, we test our code is working or not
dd(config('app.timezone'), now());
Output