Laravel timestamps() doesn't create CURRENT_TIMESTAMP

Get Off My Lawn picture Get Off My Lawn · Dec 29, 2015 · Viewed 44.4k times · Source

I have a migration that has the timestamps() method, and then I have a seed to seed this table.

Schema::create('mytable', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->timestamps();
});

The seed looks like this:

DB::table('mytable')->insert([
    [
        'title' => 'My Awesome Title'
    ]
]);

When it all gets run using:

php artisan migrate:refresh --seed

The item gets inserted, but the values of created_at and updated_at are both 0000-00-00 00:00:00 why are they not set correctly?

here are the column schemes that it creates:

`created_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',

I would like these schemes:

`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

Answer

Marcin Nabiałek picture Marcin Nabiałek · Dec 29, 2015

When you insert data not using Eloquent you need to insert timestamps on your own.

If you use:

$x = new MyTable();
$x->title = 'My Awesome Title';
$x->save();

you will have timestamp filled correctly (of course you need to create MyTable model first)

EDIT

If you really want it you can change:

$table->timestamps();

into:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

And if you create model for this table, you should set

$timestamps = false;

to make sure Eloquent won't try to set them on his way.

EDIT2

There is also one more important issue. In case you mix setting dates in tables from PHP and in other in MySQL you should make sure that both in both PHP and MySQL there's exact same datetime (and timezone) or you should use the same date comparison as you set in record (either MySQL or PHP). Otherwise when running queries you might get unexpected results for example

SELECT * FROM mytable WHERE DATE(created_at) = CURDATE()

might be different than running query with passing PHP date

"SELECT * FROM mytable WHERE DATE(created_at) = '".date('Y-m-d")."'"

because on PHP server it might be for example 2015-12-29 but on MySQL server 2015-12-30