public function scopeRestrictDays($query, String $restrictedDays = null)
{
$restrictedDays = json_decode($restrictedDays)->day ?? [];
return $query->when($restrictedDays, function ($query) {
return $query->whereNotIn(DB::raw('date_format($event->date, "%a")', restrictedDays);
});
}
Aug 12, 2021
2
Level 7
Advanced query scope
I was hoping to write an advanced query scope that would return items based on a flexible number of parameters. For example, accepting a JSON string that could have any number of days of the week inside it to be excluded from a query:
public function scopeRestrictDays($query, String $restrictedDays = null)
{
$restrictedDays = json_decode($restrictedDays)->day ?? [];
return $query->filter(function($event) use ($restrictedDays) {
$allowed = true;
foreach($restrictedDays as $day) {
if(date("D", strtotime($event->date)) === $day) {
$allowed = false;
}
}
return $allowed;
})->all();
}
This of course immediately fails because $query isn't a Collection and so I cannot use filter() on it.
Is there any way to restructure this to make it work as a query scope? I'm thinking not, but I thought I'd see if there was a Laravel genius out there that can find a way.
Please or to participate in this conversation.