Skip to content

Instantly share code, notes, and snippets.

@einnar82
Created June 9, 2023 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einnar82/41cba8c011ef41efecbb56087f2d7fe3 to your computer and use it in GitHub Desktop.
Save einnar82/41cba8c011ef41efecbb56087f2d7fe3 to your computer and use it in GitHub Desktop.
Query filter using request routes in Laravel
<?php
namespace App\Filters\Search;
use Closure;
use Illuminate\Support\Arr;
use Laravel\Scout\Builder;
class QueryParameterSearchFilter
{
protected const IN_OPERATOR = 'in';
protected const EQ_OPERATOR = 'eq';
protected const ALLOWED_OPERATORS = [
self::EQ_OPERATOR,
self::IN_OPERATOR,
];
public function handle(Builder $query, Closure $next): Builder
{
$queryParameters = Arr::except(\request()->query->all(), 'search');
foreach ($queryParameters as $queryParameter => $values) {
foreach ($values as $operator => $value) {
if (\in_array($operator, self::ALLOWED_OPERATORS) === false) {
$next($query);
continue;
}
$query = $this->resolveQueryGrammar($query, $operator, $queryParameter, $value);
}
}
return $query;
}
private function resolveQueryGrammar(
Builder $query,
string $operator,
string $queryParameter,
mixed $value
): Builder {
return match ($operator) {
self::EQ_OPERATOR => $query->where($queryParameter, $value),
default => $query->whereIn($queryParameter, (array) $value)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment