Back to Course |
Laravel 11 Eloquent: Expert Level

touch() Method To Work With updated_at

A "quick tip" lesson. Laravel has a few helper methods to update your Eloquent Model updated_at timestamp. For example, on the user Model, you have some users, and you want to update just its updated_at value without touching any other data.

You can use touch() on the Model, which will update only the updated_at field.

Since Laravel 9.25, there's a possibility to use touch() on multiple models with Eloquent query.

Records with an ID bigger than two will be updated, and the result is how many records are updated. In this example, two.


You can also touch a parent relationship Model. The relationships to be touched are defined on the Model in the $touches property as an array.

For example, you have Post and Comment Models. Comments have many Posts.

On both Post and Comment, the updated_at has the same values when they are created. After updating the comment, the updated_at column on the Post Model is also updated.


Finally, the other way around. If you don't want to auto-update the timestamp during the data update, you can set timestamps to false for that update request.

$comment->timestamps = false;
$comment->update([ ... ]);