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?
Show us the entire Eloquent query.
Aside, is the scope really that simple; I don't see the value of wrapping a where constraint?
@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)
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.
@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
@tykus my bad. I thought I gotta returned the query instance. I believe we normally do so in older versions of Laravel.
@kevinbui no, we always are modifying the same Builder instance
Please or to participate in this conversation.