Use whereMorphedTo() to query polymorphic models without manually checking both type and ID columns.
When querying polymorphic relationships (such as comments that belong to either a Post, Video, or Lesson), writing where('commentable_type', Post::class)->where('commentable_id', $post->id) is verbose.
whereMorphedTo() queries polymorphic targets directly from model instances.
Basic Usage
use App\Models\Comment;
use App\Models\Post;
$post = Post::find(1);
// Generates: WHERE commentable_type = 'App\Models\Post' AND commentable_id = 1
$comments = Comment::whereMorphedTo('commentable', $post)->get();
Querying Against Model Collections
You can also pass a collection of models to query across multiple polymorphic parents:
$posts = Post::where('featured', true)->get();
// Generates WHERE (commentable_type = 'Post' AND commentable_id IN (1, 2, 3))
$featuredComments = Comment::whereMorphedTo('commentable', $posts)->get();
Summary
- Automatically infers the polymorphic type and primary key from model instances.
- Replaces manual
where('..._type', ...)->where('..._id', ...)chains. - Supports single models and Eloquent collections.
Related Tips
View all tips →Refresh and Pessimistically Lock Models with refreshForUpdate() in Laravel 13.27
Laravel 13.27 adds refreshForUpdate(), reloading an existing model instance in-place with fresh database attributes while acquiring an exclusive FOR UPDATE row lock.
Scope Pivot Table Queries with Closures in wherePivot() in Laravel 13.26
Laravel 13.26 allows wherePivot() and orWherePivot() to accept closures, enabling direct reuse of local scopes defined on custom Pivot models.