Reputation: 1783
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
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
Reputation: 7186
This behaviour is native to MySQL. You can read about it on this documentation page:
TIMESTAMP
andDATETIME
columns have no automatic properties unless they are specified explicitly, with this exception: If theexplicit_defaults_for_timestamp
system variable is disabled, the firstTIMESTAMP
column has bothDEFAULT CURRENT_TIMESTAMP
andON UPDATE CURRENT_TIMESTAMP
if neither is specified explicitly.
The docs go on to specify that there are two strategies for avoiding this behaviour:
DEFAULT
or make the column nullable.Upvotes: 2
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