How to update a record without updating timestamp in Laravel
While working on an application, you might encounter a situation, where you don’t need to update the default timestamp field updated_at
or any custom column defined by you during development. Such as user profile visit count or page visit count where model properties aren’t updated.
So Laravel also allows us to handle it easily just by assigning false
, stops auto-updating of timestamp fields. Assigning true
will start updating back.
With Laravel it is as easy as assigning a value(true
/false
), that performs both actions based on a specified value. So that you can just start working with it. This is worth using.
Automatically updating the current timestamp into updated_at
or any custom timestamps column during Eloquent record update, is also one of the amazing features by Laravel.
Disable timestamp auto-update in Laravel
In this article, we will see How to update records without saving or updating timestamp fields either updated_at
or any other custom field. Laravel provides us functionality to handle timestamp updates while saving the model. Assigning false
to the timestamps
property of the model during model save prevents auto-update of timestamp fields.
Just follow our example as given below, to disable timestamps, only once:
How to prevent timestamps auto-update on saving in Laravel
To stop auto-update for Laravel timestamps fields, assign false
to timestamps
model property as shown below. To allow auto-update timestamps fields to assign true
, so that whenever model fields are modified; Laravel will update timestamp fields.
$model->timestamps = false;
Example without firstOrCreate()
$user = User::find(1);
// Prevents timestamps auto-update
$user->timestamps = false;
$user->increment('profile_views_count');
$user->save();
The line $user->timestamps = false;
prevents timestamp from auto-updating.
The increment()
function in $user->increment('profile_views_count');
line accepts 2 arguments:
- The first argument is the field name that needs to be increment.
- And the second argument is an amount of incrementing numeric value. The default value is 1 but it can be any number.
Read other useful Laravel model methods
- Laravel’s firstOrNew Model Method
- Laravel’s firstOrCreate Model Method
- Laravel’s Eloquent whereDate() filtering method
- Laravel’s Eloquent whereTime() filtering method
Keep helping and happy 😄 coding