This is from episode 20 of the 5.4 from scratch laravel series.
How do query scopes work exactly?
So I know there are differences from 5.6 and 5.4 but after looking through the documentation I can't figure out why this works.
public function scopeFilter($query, $filter) {
if ($month = $filter['month']) {
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if ($year = $filter['year']) {
$query->whereYear('created_at', $year);
}
}
I'm not returning $query and I'm not passing $query by reference so how is this working? Is Laravel making $query be passed by reference under the hood?
Also, for whatever reason I have to pass the $filter array to the query scope like this
['month' => request('month'), 'year' => request('year')]
even though request([month, year]) also returns an array of the exact same thing. The documentation doesn't explain why either of this is happening.
remember you are calling a method on the query object which then adds the where conditions, its not about what is returned, its about what you called on query whilst you had it
Please or to participate in this conversation.