How to Set the Default Value of a Timestamp Column to the Current Timestamp With Laravel Migrations

laravel current timestamp in migration with carbon

If you want your column to be a timestamp you should use timestamp() instead of string(). useCurrent() doesn't take a parameter. Change

$table->string('created_at')->useCurrent(Carbon::now()->timestamp);

to

$table->timestamp('created_at')->useCurrent();

https://laravel.com/docs/8.x/migrations#column-method-timestamp

https://laravel.com/docs/8.x/migrations#column-modifiers

Edit: to always get a timestamp instead of a date you can use

protected $casts = ['created_at' => 'timestamp'];

in your Model.

Add updated_at column with default value same as created_at

This would most likely be a one-off, since by default using Eloquent models, it will update both created_at and updated_at when creating a model. So after the code above, add in

DB::statement("UPDATE ".$this->tableName()." SET updated_at = created_at");

Make sure that you remove any default timestamp settings from your model, and Laravel will take it from there.

Laravel timestamps() doesn't create CURRENT_TIMESTAMP

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

Laravel. Migrations. Adding a field

Try wrapping it in DB::raw so it's executed as a SQL function:

$table->timestamp('added_on')->default(\DB::raw('CURRENT_TIMESTAMP'));

Or you can use ->useCurrent(); Laravel helper like this :

$table->timestamp('added_on')->useCurrent();


Related Topics



Leave a reply



Submit