Eloquent Touch for Models and their Relationships

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);
$user->touch();

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');
    }

}

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!';
$comment->save();

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?

Like our articles?
Check out our Laravel online courses!

3 COMMENTS

  1. great article , i just want to mention that there’s no hidden gems every thing is in the documentation you can check yourself
    laravel 5.2 :https://laravel.com/docs/5.2/eloquent-relationships#touching-parent-timestamps
    laravel 5.1 :https://laravel.com/docs/5.1/eloquent-relationships#touching-parent-timestamps
    laravel 5.0 :https://laravel.com/docs/5.0/eloquent#touching-parent-timestamps
    laravel 4.2 :https://laravel.com/docs/4.2/eloquent#touching-parent-timestamps

    the thing is that sometimes you found new features or extra info in the newer documentation

LEAVE A REPLY

Please enter your comment!
Please enter your name here