Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

joelstein
Copy link

Summary of Change

This pull request proposes adding \PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone='+00:00'" to the default MySQL connection configuration in config/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 and updated_at columns are of type TIMESTAMP, 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 an Incorrect 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.

@joelstein joelstein closed this Sep 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant