Introduction to whereAttachedTo() in Laravel 12.7
Laravel 12.7 introduces a new Eloquent query builder method called whereAttachedTo()
, designed to simplify querying models that are attached to other models via a BelongsToMany
relationship. This method provides a cleaner and more expressive way to filter models based on their attachments in pivot tables.
The Problem It Solves
Before the introduction of whereAttachedTo()
, developers had to use whereHas()
or whereIn()
with nested relationship queries to filter models attached to specific instances or collections. This approach could be verbose and less readable.
The Solution: whereAttachedTo()
The whereAttachedTo()
method allows you to query models that are attached to a given model or set of models through a BelongsToMany
relationship. It guesses the relationship name based on Laravel conventions but also allows you to specify it manually.
Examples
Before Laravel 12.7:
$tags = Tag::where('created_at', '>', now()->subMonth())->get();
$taggedPosts = Post::whereHas('tags', function ($query) use ($tags) {
$query->whereKey($tags);
})->get();
After Laravel 12.7:
$tags = Tag::where('created_at', '>', now()->subMonth())->get();
$taggedPosts = Post::whereAttachedTo($tags)->get();
// Specifying the relationship name manually
$taggedPosts = Post::whereAttachedTo($tags, 'tags')->get();
Key Features
- Simplifies Many-to-Many Relationship Queries: Reduces the complexity of filtering models based on their attachments.
- Expressive Syntax: Provides a clear and readable way to define queries.
- Conventional Relationship Guessing: Automatically determines the relationship name based on the model class, but allows manual specification if needed.
Latest from laravel
Bookmark This Article
Your browser doesn't support automatic bookmarking. You can:
- Press Ctrl+D (or Command+D on Mac) to bookmark this page
- Or drag this link to your bookmarks bar:
Clicking this bookmarklet when on any page of our site will bookmark the current page.
Conclusion
The whereAttachedTo()
method in Laravel 12.7 enhances the Eloquent ORM by offering a more straightforward and expressive way to handle BelongsToMany
relationships, making it easier for developers to query attached models efficiently.