kodfire
kodfire

Reputation: 1783

Laravel automatically add "on update CURRENT_TIMESTAMP" to some certain columns

My migration is like so:

$table->bigIncrements('id');
$table->timestamp('from_date');
$table->timestamp('to_date');
$table->timestamps();

The problem is that when I migrate it, the second one which is from_date automatically gets on update CURRENT_TIMESTAMP attribute so it means when I update other columns this column will be updated too. That's what I don't want. How can I prevent it?

Upvotes: 2

Views: 3064

Answers (3)

Alan
Alan

Reputation: 396

You need to make the DateTime column nullable, then MySQL won't add that. By default, MySQL adds that to the first timestamp in the table, unless explicitly told not to (via allowing a null value for the field). This is a MySQL thing, not a Laravel thing.

$table->timestamp('colName')->nullable();

Read :

Automatic Initialization and Updating for TIMESTAMP and DATETIME - MYSQL DOCS

Laravel & MySQL auto-adding “on update current_timestamp()” to timestamp fields

Source : laracasts - How can I stop Laravel from making timestamps on update CURRENT_TIMESTAMP?

Upvotes: 3

Daniel Buckmaster
Daniel Buckmaster

Reputation: 7186

This behaviour is native to MySQL. You can read about it on this documentation page:

TIMESTAMP and DATETIME columns have no automatic properties unless they are specified explicitly, with this exception: If the explicit_defaults_for_timestamp system variable is disabled, the first TIMESTAMP column has both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP if neither is specified explicitly.

The docs go on to specify that there are two strategies for avoiding this behaviour:

  • Enable the explicit_defaults_for_timestamp variable in your database configuration.
  • When defining your timestamp column, specify a DEFAULT or make the column nullable.

Upvotes: 2

nakov
nakov

Reputation: 14278

You can add nullable to the column in order to remove the constraint.

$table->timestamp('from_date')->nullable();

Unfortunately I think that this is the only solution. Then you can add a form validation in order to prevent setting null value for the field.

-- EDIT

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

// or
$table->timestamp('from_date')->useCurrent();

Try this as well, I believe this is what the created_at has.

Upvotes: 1

Related Questions