Automatically Update Parent Timestamps with Laravel #[Touches]
Automatically Update Parent Timestamps with Laravel #[Touches]
Imagine you have a blog post with many comments.
When a comment is updated, you may also want the post's updated_at timestamp to change.
Normally, you might manually update the post:
$comment->save();
$comment->post->touch();
Laravel provides a cleaner way to handle this automatically.
Use the #[Touches] Attribute
On the child model, add the #[Touches] attribute:
use Illuminate\Database\Eloquent\Attributes\Touches;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Touches(['post'])]
class Comment extends Model
{
public function post(): BelongsTo{
return $this->belongsTo(Post::class);
}
}
Now, when the comment is updated using Eloquent's save() method, Laravel will also update the updated_at timestamp of its related post.
Real-World Example
Suppose you update a comment:
$comment->content = 'Updated comment';
$comment->save();
Laravel updates:
comments.updated_at
and automatically touches:
posts.updated_at
You don't need to call touch() manually.