I would like to make a timestamp column with a default value of CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
using the Laravel Schema Builder/Migrations. I have gone through the Laravel documentation several times and I don't see how I can make that the default for a timestamp column.
The timestamps()
function makes the defaults 0000-00-00 00:00
for both columns that it makes.
To create both of the
created_at
andupdated_at
columns:You will need MySQL version >= 5.6.5 to have multiple columns with
CURRENT_TIMESTAMP
In Laravel 5 simply:
Documentation: http://laravel.com/docs/5.1/migrations#creating-columns
Usethe following:
$table->timestamp('created_at')->nullable();
Hopefully, it will help you. Thank you.
Since it's a raw expression, you should use
DB::raw()
to setCURRENT_TIMESTAMP
as a default value for a column:This works flawlessly on every database driver.
As of Laravel 5.1.25 (see PR 10962 and commit 15c487fe) you can use the new
useCurrent()
column modifier method to set theCURRENT_TIMESTAMP
as a default value for a column:As asked, on MySQL you could also use the
ON UPDATE
clause throughDB::raw()
:Gotchas
MySQL
Starting with MySQL 5.7,
0000-00-00 00:00:00
is no longer considered a valid date. As documented at the Laravel 5.2 upgrade guide, all timestamp columns should receive a valid default value when you insert records into your database. You may use theuseCurrent()
column modifier (from Laravel 5.1.25 and above) in your migrations to default the timestamp columns to the current timestamps, or you may make the timestampsnullable()
to allow null values.PostgreSQL & Laravel 4.x
In Laravel 4.x versions, the PostgreSQL driver was using the default database precision to store timestamp values. When using the
CURRENT_TIMESTAMP
function on a column with a default precision, PostgreSQL generates a timestamp with the higher precision available, thus generating a timestamp with a fractional second part - see this SQL fiddle.This will led Carbon to fail parsing a timestamp since it won't be expecting microseconds being stored. To avoid this unexpected behavior breaking your application you have to explicitly give a zero precision to the
CURRENT_TIMESTAMP
function as below:Since Laravel 5.0,
timestamp()
columns has been changed to use a default precision of zero which avoids this.Thanks to @andrewhl for pointing out this issue in the comments.
Starting from Laravel 5.1.26, tagged on 2015-12-02, a
useCurrent()
modifier has been added:PR 10962 (followed by commit 15c487fe) leaded to this addition.
You may also want to read issues 3602 and 11518 which are of interest.
Basically, MySQL 5.7 (with default config) requires you to define either a default value or nullable for time fields.
Use Paulo Freitas suggestion instead.
Until Laravel fixes this, you can run a standard database query after theSchema::create
have been run.It worked wonders for me.