New in Laravel 12.7: `whereAttachedTo()` for BelongsToMany Relationships


- whereAttachedTo() for BelongsToMany Relationships
- The Problem
- The Solution: whereAttachedTo()
- Examples
whereAttachedTo()
for BelongsToMany Relationships
Laravel has introduced a new query builder method, whereAttachedTo()
, contributed by @bakerkretzmar, that simplifies querying BelongsToMany
relationships. Merged into the framework on April 2, 2025, this feature brings a more expressive and convenient way to filter models based on their pivot table attachments.
The Problem
When dealing with many-to-many relationships in Eloquent, developers often need to filter models that are attached to a given instance or a collection of instances. This previously required manual use of whereHas
or whereIn
logic with nested relationship queries, which could be verbose and less readable.
whereAttachedTo()
The Solution: The new whereAttachedTo()
method provides a clean, expressive alternative. Inspired by the existing whereBelongsTo()
method, it allows developers to query for models that are attached to a given model or set of models through a BelongsToMany
relationship.
Examples
Before:
$tags = Tag::where('created_at', '>', now()->subMonth())->get(); $taggedPosts = Post::whereHas('tags', function ($query) use ($tags) { $query->whereKey($tags);})->get();
After:
$tags = Tag::where('created_at', '>', now()->subMonth())->get(); $taggedPosts = Post::whereAttachedTo($tags)->get();
Like whereBelongsTo(), whereAttachedTo() guesses the relationship name based on Laravel conventions, but it can also be passed in manually:
$taggedPosts = Post::whereAttachedTo($tags, 'tags')->get();
Stay Updated.
I'll you email you as soon as new, fresh content is published.