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();