Loading episodes…
0:00 0:00

Introduction to whereAttachedTo() in Laravel 12.7

00:00
BACK TO HOME

Introduction to whereAttachedTo() in Laravel 12.7

10xTeam April 16, 2025 2 min read

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.

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.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?