Home » Php » Laravel and MySQL not playing well in case of DateTime

Laravel and MySQL not playing well in case of DateTime

Posted by: admin November 29, 2017 Leave a comment

Questions:

I created a webapp using Laravel and SQLite,everything was going great.Now,I want to use MySQL as database but now I am unable to add data to my tables.

This is the field from my migration:

$table->dateTime('last_updated')->nullable();

and this is how I am populating the field using laravel:

$client->last_updated = time();

But it is giving me error like:

Illuminate \ Database \ QueryException
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1402140378' for column 'last_updated' at row 1 (SQL: update `clients` set `last_updated` = 1402140378 where `id` = 1)

Any help will be appreciated.

Answers:

$table->dateTime creates an DATETIME column in your database that expects a value of YYYY-MM-DD HH:ii:ss. What you’re inserting is a unix timestamp.

You can either use Carbon (requires use Carbon\Carbon at the top of your file),

$client->last_updated = Carbon::now()

date(...),

$client->last_updated = date('Y-m-d H:i:s') 

or PHP’s DateTime class to insert the current datetime to the database..

Leave a Reply

Your email address will not be published. Required fields are marked *