How Set Application Timezone in Laravel
Table of contents
To ensure timestamps in your Laravel application are stored in a specific timezone (e.g., Qatar timezone), you need to set the application timezone in the configuration file and ensure your database is configured to handle this correctly.
Here’s a step-by-step guide to achieve this:
1. Set Application Timezone:
Open the config/app.php file and set the timezone option to Asia/Qatar:
'timezone' => 'Asia/Qatar',
2.Configure Database Timezone:
Laravel stores timestamps in UTC by default and then converts them to the application timezone. To ensure this is handled correctly, you might want to set the timezone configuration for your database connection. For MySQL, this involves setting the timezone configuration in your MySQL connection settings.
Open your config/database.php file and find your MySQL connection configuration. Add the timezone option:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
'timezone' => '+03:00', // Qatar Timezone
],
3. Ensure Database Tables Use the Correct Timezone:
If you want to ensure the timestamps are stored in the Qatar timezone in the database, you might need to configure your MySQL server to use the correct timezone. This can be done by setting the timezone in your MySQL server configuration (my.cnf or my.ini file):
[mysqld]
default-time-zone = '+03:00'
3. Alternatively, you can run the following SQL command to set the timezone for the current session:
SET time_zone = '+03:00';
By setting the application timezone to Asia/Qatar and configuring the MySQL connection to use the Qatar timezone, your timestamps should be correctly stored and retrieved according to the Qatar timezone.
Subscribe to my newsletter
Read articles from Aymen Tucker directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by