Eloquent Touch for Models and their Relationships

Tutorial last revisioned on August 18, 2022 with Laravel 9
There are two "tricks" I want to show you here. Probably you will know one of them, but might not know the other one. So, you know there are fields created_at and updated_at in Eloquent tables, right? The thing is that we can update them even without updating any data in the row. See the code here:
$user = User::find(1);
It will actually update only updated_at column with current timestamp, without touching any other field. It can be useful if you want to save, for example, last time the record was processed for something. But not only that - there's a second trick, as I promised. You can also "touch" relationships by providing their names in Eloquent Model properties. Like this:
class Comment extends Model {

    protected $touches = ['post'];

    public function post()
        return $this->belongsTo(Post::class);

See the array called $touches? This is where you put all the relationships you want to get updated_at as soon as this Model is updated. So, for example:
$comment = Comment::find(1);
$comment->text = 'Edit to this comment!';
In this case related Post row for this comment will get a new updated_at value. This is really really useful if one entity has a lot of child relationships and you want to get its updated time without checking all children relationship updates. Finally, I want to encourage you to sometimes read the source of the "inner" side of Laravel - there's a lot of hidden gems which are not in the documentation. For example, this $touches and other undocumented properties can be found by looking at this GitHub file. Impressive, isn't it?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by