Default MySQL Timezone to UTC #6673
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary of Change
This pull request proposes adding
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone='+00:00'"
to the default MySQL connection configuration inconfig/database.php
. This change ensures that all MySQL connections initiated by Laravel have their session time zone explicitly set to UTC.Problem Description
Laravel handles and stores timestamps in UTC. The default
created_at
andupdated_at
columns are of typeTIMESTAMP
, which is a timezone-aware column type in MySQL.A common and confusing issue arises when a developer's local MySQL server's time zone defaults to a DST-observing time zone (e.g., America/Chicago). On the day the clock "springs forward" for Daylight Saving Time, there is a one-hour period (e.g., from 2:00 AM to 3:00 AM) that does not exist.
If a Laravel application attempts to insert a record at a time within this non-existent hour (e.g.,
2025-03-09 02:30:00
), the MySQL database will throw anIncorrect datetime value
error.This is a frustrating "works on my machine" bug because:
Laravel's internal Carbon objects are valid UTC times.
The error only occurs on systems where the database session's time zone is local and DST is observed.
Production environments typically have their database server time zones set to UTC, so the bug is never seen there.
Proposed Solution
By adding the
MYSQL_ATTR_INIT_COMMAND
option, we can force the MySQL session time zone to UTC. This aligns the database's behavior with Laravel's internal logic, preventing the time zone conversion from a non-existent local time to a valid UTC time.Benefits
Improved Developer Experience: Prevents a confusing and time-consuming bug right out of the box, especially for developers on local machines.
Increased Robustness: Makes Laravel's
TIMESTAMP
handling more resilient to variations in database server configuration.Consistency: Ensures that time zone handling is consistent across all environments (local, staging, production) without requiring manual configuration.
Best Practice: Aligns with the widely accepted best practice of storing all timestamps in UTC.