panthro's avatar

Calling a scope when eager loading?

I implement a scope as per the docs:

 public function scopeCollection(Builder $query, string $collection = 'default'): void
{
    $query->where('collection', $collection);
}

How can I eager load and constrain via the scope?

 'media' => function (Builder $query) {
     $query->collection('my-collection');
 },

The above does not work?

0 likes
6 replies
tykus's avatar

Show us the entire Eloquent query.

Aside, is the scope really that simple; I don't see the value of wrapping a where constraint?

panthro's avatar

@tykus the actual scope may be expanded, i wanted a light example for a question.

The entire query is:

Post::with([
                'classification',
                'media' => function (Builder $query) {
                    $query->collection('my-collection');
                },
            ])->cursorPaginate(36)
kevinbui's avatar

You can definitely use query scopes for eager loading.

Pls remember to return the query instance:

 public function scopeCollection(Builder $query, string $collection = 'default')
{
    return $query->where('collection', $collection);
}

In addition, this definition of collection clashes with the Laravel collection. I suggest using a different term if possible.

tykus's avatar

@kevinbui this is not relevant at all... note the void return type on the scope method!

Pls remember to return the query instance

Again, this is not true at all; there is no collection method on Eloquent models by default.

this definition of collection clashes with the Laravel collection

1 like
kevinbui's avatar

@tykus my bad. I thought I gotta returned the query instance. I believe we normally do so in older versions of Laravel.

tykus's avatar

@kevinbui no, we always are modifying the same Builder instance

1 like

Please or to participate in this conversation.