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 hav
To create both of the created_at
and updated_at
columns:
$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
You will need MySQL version >= 5.6.5 to have multiple columns with CURRENT_TIMESTAMP
Use Paulo Freitas suggestion instead.
Until Laravel fixes this, you can run a standard database query after the Schema::create
have been run.
Schema::create("users", function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('given_name', 100);
$table->string('family_name', 100);
$table->timestamp('joined');
$table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
$table->string('timezone', 30)->default('UTC');
$table->text('about');
});
DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");
It worked wonders for me.
This doesn't work for a fact:
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP');
It doesn't remove the 'default 0' that seems to come with selecting timestamp and it just appends the custom default. But we kind of need it without the quotes. Not everything that manipulates a DB is coming from Laravel4. That's his point. He wants custom defaults on certain columns like:
$table->timestamps()->default('CURRENT_TIMESTAMP');
I don't think it's possible with Laravel. I've been searching for an hour now to see whether it's possible.
Update: Paulos Freita's answer shows that it is possible, but the syntax isn't straightforward.
This is how you do it, I have checked it and it works on my Laravel 4.2.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
Hope this helps.
Starting from Laravel 5.1.26, tagged on 2015-12-02, a useCurrent()
modifier has been added:
Schema::table('users', function ($table) {
$table->timestamp('created')->useCurrent();
});
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.
In Laravel 5 simply:
$table->timestamps(); //Adds created_at and updated_at columns.
Documentation: http://laravel.com/docs/5.1/migrations#creating-columns