PaulJasiul's avatar

How to use multiple filters in Spatie Query Builder

Hello, I have a problem with multiple filters when using Spatie Query Builder. When both filters have $query->with(...) then the last one overrides previous. Any ideas how to merge then or fix it?

Allowed filters:

$this->allowedFilters([
            AllowedFilter::custom('date', new FiltersEventDate),
            AllowedFilter::custom('theaters', new FiltersMovieTheater),
        ]);

Date Filter:

$date = (new Carbon($value))->toDateString();

        $query
            ->whereHas('events', function (Builder $query) use ($date) {
                return $query->whereDate('starts_at', $date);
            })
            ->with(['events' => function ($query) use ($date) {
                return $query->whereDate('starts_at', $date);
            }]);

Theater Filter:

$query
            ->whereHas('events', function (Builder $query) use ($value) {
                return $query->whereHas('theaterHall', function (Builder $query) use ($value) {
                    return $query->whereHas('theater', function (Builder $query) use ($value) {
                        return $query->whereIn('id', $value);
                    });
                });
            })
            ->with(['events' => function ($query) use ($value) {
                return $query->whereHas('theaterHall', function ($query) use ($value) {
                    return $query->whereHas('theater', function ($query) use ($value) {
                        return $query->whereIn('id', $value);
                    });
                });
            }]);
0 likes
5 replies
bobbybouwmann's avatar
Level 88

Well, Laravel can only include the events once. So if you need both, you need to build up the query you want to use for events by combining both filters in the callback and then call it using with.

Same goes for the whereHas part. So if you really want this you should combine the two in one filter, that is the easiest solution here ;)

2 likes
PaulJasiul's avatar

Yes, because I didn't find another way I combined both filters. And now everything works fine. But thank you for your answer. :)

Please or to participate in this conversation.