Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Mariabdb Avoid Invalid datetime format: when date is empty

David Carr

Development

When inserting records any columns with a datatype set to date which are empty will generate this error: 

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime

The reason for this by default MariaDB’s sql mode has NO_ZERO_DATE which won’t allow zero dates to be entered only valid or null is allowed.

You have 2 options here:

  1. Change this setting in the database config file 
  2. ensure empty dates are set to null

I’ve chosen to leave the default in place and always pass null for empty dates, ternary operators make this simple:

$startDate = ($startDate !='') ? date('Y-m-d', strtotime($startDate)) : null;

The above says if the date is not empty then convert the date into the correct format otherwise pass null.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.