Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0000-00-00 as date in Laravel

I have to build a Laravel application on an existing (old) database. This database uses 0000-00-00 as default dates. There is no way I can change this because the current system (which will also be kept) uses this to check if something is active for an infinite amount of time (for example: active_from 0000-00-00 & active_till 0000-00-00 means it's always active).

I want to add a column to an existing table, so I created a migration: add_columnname_to_tablename_table. In the up() function I did: $table->string('columnname'). When I run the migration, I get:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '0000-00-00 00:00:00' for column active_from at row 1.

The old system is too big to make any changes to this -- and I'm not allowed to change it.

Is there any way to make Laravel accept 0000-00-00 as a valid date(time)?

like image 362
Kenny Hietbrink Avatar asked Jul 11 '18 14:07

Kenny Hietbrink


People also ask

What is laravel date format?

Database should be always YYYY-MM-DD; Laravel back-end: in forms/views we should have whatever format client wants, but while saving to database it should be converted to YYYY-MM-DD; JavaScript datepicker: JS formats for dates are not the same as PHP formats, we will see that below in the example.

What is Time () in laravel?

What is time () in Laravel? The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

How do I change the date format in laravel query?

You can always use Carbon's ->format('m/d/Y'); to change format. Or you can just use selectRaw to build your queries. Save this answer.


2 Answers

Laravel uses strict mode by default, I have fixed this by changing strict => true in config/database.php to strict => false.

like image 71
Kenny Hietbrink Avatar answered Sep 22 '22 13:09

Kenny Hietbrink


strtotime will return a number below zero when the date is invalid such as common in MySQL 0000-00-00 00:00:00. Make sure you pass an object type date or carbon:

  return strtotime(date or carbon object) < 0 ? null : date
like image 30
Matteus Barbosa Avatar answered Sep 22 '22 13:09

Matteus Barbosa