Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Belongs To Through Laravel Package

staudenmeir/belongs-to-through

Add BelongsToThrough relationships to Eloquent: the inverse of HasManyThrough. Define belongs-to chains across unlimited intermediate models, with support for custom keys, table aliases, and soft deletes. Works with Laravel 5+.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing the package via Composer (composer require staudenmeir/belongs-to-through:^2.17 for Laravel 12) and adding the BelongsToThrough trait to any model needing inverse deep relationships. The most common first use case is reversing a HasManyThrough chain like Country -> Users -> Posts to allow Post to access its ultimate Country via User. Define the relationship like so:

class Post extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

    public function country()
    {
        return $this->belongsToThrough(Country::class, User::class);
    }
}

Then access it naturally: $post->country->name. Eager load with with('country') as usual.

Implementation Patterns

  • Deep chaining: Extend beyond two hops with arrays: belongsToThrough(Grandparent::class, [Parent::class, Child::class]).
  • Bidirectional access: Pair hasManyThrough in parent models with belongsToThrough in leaf models for natural navigation both ways (e.g., UserPostsTagsTagPostsUser).
  • Nested eager loading: Combine with standard relationships (with('user.country')) and use whereBelongsToThrough() constraints where supported.
  • Scoping & filtering: Use query constraints like ->where('status', 'active') on the relationship; apply withTrashed() for soft-deletable intermediate models.
  • Laravel Nova integration: Use BelongsToThrough fields directly in resource forms (v2.9+), leveraging the same chain definitions.

Gotchas and Tips

  • Key naming ambiguity: Laravel cannot auto-detect composite keys. Always specify foreignKeyLookup and localKeyLookup arrays when using non-standard keys (e.g., foreignKeyLookup: [Intermediate::class => 'custom_id']).
  • Table aliasing: For repeated models in the chain (e.g., self-referencing comments), use HasTableAlias trait and pass 'ModelName as alias' as the intermediate class string.
  • Soft delete gotcha: By default, withTrashed() fails on intermediate models; explicitly pass column aliases like ->withTrashed('users.deleted_at') to include soft-deleted intermediates.
  • Eager loading quirks: Avoid deep nesting if query plans become inefficient; consider denormalizing or materialized views for critical hot paths.
  • IDE support: Install laravel-ide-helper (v2.15+) and enable PHPStan level 9+ with the updated generics to get reliable autocompletion for chained belongsToThrough results.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport