🎉🎉 Larasense is officially launched 🎉🎉
- Your Hub for Laravel News, Trends & Updates

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

laravel
release
eloquent
Nabil Hassen
Nabil Hassen
Apr 8, 2025
whereAttachedTo for BelongsToMany Relationships
Last updated on Apr 8, 2025
Table of contents:

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.

The Solution: whereAttachedTo()

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();
Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts