CodexBloom - Programming Q&A Platform

Laravel 10: implementing Soft Deletes in Polymorphic Relationships

👀 Views: 16 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
laravel soft-deletes polymorphic-relationships PHP

I'm relatively new to this, so bear with me. I'm working with an scenario with soft deletes in a polymorphic relationship in Laravel 10. I have a `comments` table that can belong to various models (like `post` and `video`) through a polymorphic relationship. Each comment is soft-deletable. The question arises when attempting to retrieve comments after they have been soft deleted. I expect the deleted comments to be excluded from the query, but I'm still seeing them. My models are set up like this: ```php // Comment model class Comment extends Model { use SoftDeletes; public function commentable() { return $this->morphTo(); } } // Post model class Post extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } } // Video model class Video extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } } ``` I'm trying to fetch all comments for a post as follows: ```php $post = Post::find(1); $comments = $post->comments; ``` However, even after soft deleting a comment, it still shows up in the `$comments` collection. I've tried using the `withTrashed()` method, but it doesn't seem applicable here since I want to exclude deleted comments entirely. I've also verified that the `deleted_at` column is being populated correctly in the database. I even created a new comment and deleted it, but it still appears in the collection. Any insights on what might be going wrong or how to properly filter out soft-deleted comments from a polymorphic relationship? Thanks for your help! Any help would be greatly appreciated!