Framework: [Proposal] Default value for Timestamp columns

Created on 18 Feb 2013  路  7Comments  路  Source: laravel/framework

I posted a question at #368 a bit earlier that I should have investigated more before posting. Sorry for that.

But one question regarding this still remains: apparently you can't set a default value of CURRENT_TIMESTAMP at this point for timestamp columns because setting a default value through the DB scheme creator is currently hardcoded with single quotes around the values.

/**
 * Get the SQL for a default column modifier.
 *
 * @param  Illuminate\Database\Schema\Blueprint  $blueprint
 * @param  Illuminate\Support\Fluent  $column
 * @return string|null
 */
protected function modifyDefault(Blueprint $blueprint, Fluent $column)
{
    if ( ! is_null($column->default))
    {
        return " default '".$this->getDefaultValue($column->default)."'";
    }
}

Because of this you can't set default SQL constant values like CURRENT_TIMESTAMP because default 'CURRENT_TIMESTAMP' will return a syntax error for your SQL query.

Can this perhaps be reviewed so you can set SQL constants as default values?

Most helpful comment

you can use:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

It would better be the default behaviour. So one could just use $table->timestamps() and wouldn't have to notice the situation and look for a solution.

All 7 comments

@taylorotwell If you're interested in this, I could come up with a pull request for a wrapValue() method in the Grammar class. Something like that.

I'm having the same problem. I want to do something like this:

$table->timestamp('updated_at')->default('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');

I know Laravel will update it automatically but I prefer the DB to be more responsible with data integrity as Laravel and web are not the only ways for data to be affected in our env.

default now supports being passed stuff from DB::raw so you should be able to pass whatever you want now.

So how can we do this in a migration in L3?

you can use:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

It would better be the default behaviour. So one could just use $table->timestamps() and wouldn't have to notice the situation and look for a solution.

where did the DB class came from? what's the complete namespace location?
Thanks @DeadDuck

@romack15 the DB class is actually a Facade for Laravel's DB component. Check http://laravel.com/docs/5.1/facades#facade-class-reference for more info :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iivanov2 picture iivanov2  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

ghost picture ghost  路  3Comments

digirew picture digirew  路  3Comments