What Is Touching Parent Timestamps In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.Today we are going to discuss how can we use Touching Parent Timestamps in laravel and for what we use Touching Parent Timestamps in laravel with example.

What Is Touching Parent Timestamps In Laravel With Example

Touching Parent Timestamps

To learn more about One To Many Relationships visit our Bajarangisoft site

When a model belongsTo or belongsToMany another model, such as a Comment which belongs to a Post, it is sometimes helpful to update the parent's timestamp when the child model is updated. For example, when a Comment model is updated, you may want to automatically "touch" the updated_at timestamp of the owning Post. Eloquent makes it easy. Just add a touches property containing the names of the relationships to the child model:

 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * All of the relationships to be touched.
     *
     * @var array
     */
    protected $touches = ['post'];

    /**
     * Get the post that the comment belongs to.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}
 

Now, when you update a Comment, the owning Post will have its updated_at column updated as well, making it more convenient to know when to invalidate a cache of the Post model:

$comment = App\Comment::find(1);

$comment->text = 'Edit to this comment!';

$comment->save();

Related Post