Reputation: 432
I am trying to update a parent of a parents updated_at timestamp when the child model is updated. I can updated the parent model using the following code inside the child model
protected $touches = ['post']
but for example if I also wanted to update the user who made the posts updated_at timestamp how would I do this?
I was hoping I could just add the following code to the Post.php model
protected $touches = ['user']
but this doesn't seem to work, the user model timestamp only gets updated if the Post record is updated.
Upvotes: 2
Views: 833
Reputation: 1523
Perhaps something like Model Events could help you?...
Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::updated(function ($post) {
$post->user->touch();
});
}
}
This is assuming that your Post has a User relationship defined.
Here we are listening for the updated
event on the Post
. When that event is triggered, the associated User
is touched.
Upvotes: 1