Skip to content

Scopes not resolved on relation chains #646

@alies-dev

Description

@alies-dev

Problem

When calling a model scope through a relation chain, the plugin does not resolve it.

class Post extends Model
{
    public function scopePublished(Builder $query): Builder
    {
        return $query->where('published', true);
    }
}

class User extends Model
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

// ❌ UndefinedMagicMethod — "published" not found
$user->posts()->published()->get();

// ✅ These work (handled by MethodForwardingHandler)
$user->posts()->where('published', true)->get();
$user->posts()->orderBy('created_at')->get();

Cause

MethodForwardingHandler searches EloquentBuilder and QueryBuilder for forwarded methods, but does not check the related model for scope{Name}() methods or #[Scope] attributes.

Fix

When resolving a forwarded method on a Relation:

  1. Extract TRelatedModel from the relation's generic params
  2. Check the related model's class storage for scope{MethodName}() or #[Scope] attribute methods
  3. If found, return the relation type (self-returning / fluent)

Related

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions