Reputation: 4107
There have been a lot of questions asking how one can prevent the updated_at
column from changing when nothing was changed. In fact, this was even fixed as a bug.
However, I would like to do just the opposite. I wish to update the updated_at
column to the current timestamp, despite nothing being changed. Essentially, I would like to touch
my model if you will.
$ touch MyLaravelModel
Is there a easy way to do something like this in Laravel? Something equivalent to $model->touch()
as opposed to manually editing the field?
I have already tried something like this, but absolutely nothing happens.
$model = Model::find(1);
$model->save();
The reason I'm doing this is because I would like to use the updated_at
column to essentially keep track of when the model was last "viewed", without necessarily changing it. Is there a better way to go about this?
This is different from Touching Parent Timestamp because in this case, my model does not belong to a parent nor does it have any children.
Upvotes: 1
Views: 464
Reputation: 7879
You could use the touch()
method. It's in the Model
abstract class and has been since at least v4.0.
Here it is:
/**
* Update the model's update timestamp.
*
* @return bool
*/
public function touch()
{
$this->updateTimestamps();
return $this->save();
}
Use it like this:
$model->touch();
Upvotes: 1
Reputation: 3534
I believe you can do myObject->save() and that will update the updated_at field of the current object even if nothing was changed. So lets say it was a user:
$myUser = User::find(1);
$myUser->save()
I believe that would still update the updated_at time.
Upvotes: 0