PHP code example of jpnut / eloquent-nested-filter
1. Go to this page and download the library: Download jpnut/eloquent-nested-filter library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jpnut / eloquent-nested-filter example snippets
...
class ProductFilter extends AbstractFilter
{
public ?StringFilterObject $name;
}
...
$filter = new ProductFilter([
'or' => [
[
'name' => [
'value' => 'foo',
'operator' => 'BEGINS',
]
],
[
'name' => [
'value' => 'foo',
'operator' => 'ENDS',
]
],
]
]);
$query = $filter->filter(Product::query());
...
// app/ProductFilter.php
namespace App;
...
class ProductFilter extends AbstractFilter
{
public ?IDFilterObject $id = null;
public ?StringFilterObject $name = null;
public ?NumberFilterObject $amount = null;
public ?BooleanFilterObject $in_stock = null;
public ?DateFilterObject $created_at = null;
/** @var \App\CategoryFilter[]|null */
public ?array $category = null;
}
...
$filter = new ProductFilter([
'or' => [
[
'name' => [
'value' => 'foo',
'operator' => 'BEGINS',
]
],
[
'name' => [
'value' => 'foo',
'operator' => 'ENDS',
]
],
]
]);
...
...
$filter = $request->has('filter')
? new ProductFilter(json_decode($request->query('filter'), true))
: null;
...
...
$results = $filter->query(Product::query()->withTrashed())->get();
...
abstract public function filter(string $name, Builder $query): Builder;
abstract public static function fromArray(array $properties = []): self;
public function filter(string $name, Builder $query): Builder
{
if ($this->operator->equals(Operator::IS())) {
return $query->where($name, $this->value);
}
if ($this->operator->equals(Operator::IS_NOT())) {
return $query->where($name, '<>', $this->value);
}
...
throw $this->invalidOperator($this->operator);
}
public static function fromArray(array $properties = []): self
{
return new static(
is_null($properties['value'] ?? null) ? null : floatval($properties['value']),
static::operatorFromProperties($properties)
);
}
...
class ProductFilter extends AbstractFilter
{
protected ?int $max_depth = 5;
protected ?int $max_filters = 50;
}
...