Backend Discussion Laravel PHP

Touching Parents Timestamps with “$touches” in Laravel

When you’d need to update updated_at field of parent model, you can just use $touches of Laravel eloquent.

Let’s assume, you have Posts and each Post has multiple Comments.
Then it’s one to many relationship between Post and Comments.
If a user added a comment for the post, we should update updated_at of the post as well.
We can do this with $touches variable of Laravel.

class Comment extends Model
{
    protected $touches = ['post'];

    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

With

With above model, if you call this code $comment->save();, it will update the updated_at field of posts table.
That is, touches update the updated_at field that is related to its model.
This will be useful for update datetime of Post whenever anybody update its comments as an example.
https://laravel.com/docs/5.6/eloquent-relationships#touching-parent-timestamps (edited)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *