PHP
Querying Polymorphic Relationships by Related Type
Learn to query records based on the specific type of a related polymorphic model, enabling targeted data retrieval from complex relationships.
// Assuming Comment model has morphTo 'commentable' relation
use App\Models\Comment;
use App\Models\Post;
use App\Models\Video;
// Retrieve comments made on Posts
$postComments = Comment::whereHasMorph(
'commentable',
[Post::class],
function ($query) {
$query->where('title', 'LIKE', '%Laravel%'); // Condition on the Post model
}
)->get();
// Retrieve comments made on Videos, or specific Posts
$specificComments = Comment::whereHasMorph(
'commentable',
[Video::class, Post::class],
function ($query, $type) {
if ($type === Post::class) {
$query->where('category', 'Technology');
} elseif ($type === Video::class) {
$query->where('duration', '>', 300); // 5 minutes
}
}
)->get();
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. The `whereHasMorph` method helps query records based on the specific *type* of the related polymorphic model. The first argument is the name of the polymorphic relationship (e.g., 'commentable'). The second is an array of related model classes you want to filter by. An optional third argument is a closure to add further conditions on the related models themselves, allowing precise control over which polymorphic relationships are included.