cetria / laravel-filter
A simple Laravel library enabling sending filters in query requests.
2.2.0
2025-02-12 09:45 UTC
Requires
- php: ^8.2
- laravel/framework: >=11
Requires (Dev)
- cetria/laravel-dummy-models: ~1.3.1
- cetria/reflection-helper: ^0.3.0
- phpunit/phpunit: >=11
README
A simple Laravel library enabling sending filters in query requests.
Installation
Install the library using Composer:
composer require cetria/laravel-filter
Inject trait in your models for extension query builder:
class User extends Model
{
use \Cetria\Laravel\Filter\Traits\ExtensionForModel;
}
Usage
Create Filter Query
use Cetria\Laravel\Filter\Filter;
use Cetria\Laravel\Filter\Condition;
use Cetria\Laravel\Filter\Operator;
// Create a new instance of the filter
$filter = new Filter();
//Create a new instance of the Conditoon
$conditionPrice = new Condition('price', Operator::LTE->name, 5000);
// Push Conditon to FilterInstance
$filter->addScope($conditionPrice);
// Apply filter in your query
$builder = YourModel::query();
$filter->apply($builder);
// Result
$result = $builder->get();
Create Filter Query With More dimmensions
use Cetria\Laravel\Filter\Filter;
use Cetria\Laravel\Filter\Condition;
use Cetria\Laravel\Filter\Operator;
$filter = new Filter();
$conditionPrice = new Condition('price', Operator::LTE, 5000);
$filter->addScope($conditionPrice);
$filter->addScope(
(new Filter())
->addScope(new Condition('created_at', Operator::GT, '2020-01-01', 'OR'))
->addScope(new Condition('price', Operator::LTE, 4000))
)
// Result Where price <= 5000 OR (created_at > '2020-01-01' AND price <= 4000)
Create Collection Query
use Cetria\Laravel\Filter\Filter;
use Cetria\Laravel\Filter\Condition;
use Cetria\Laravel\Filter\Operator;
// Create a new instance of the filter
$filter = new Filter();
//Create a new instance of the Conditoon
$conditionPrice = new Condition('price', Operator::LTE, 5000);
// Push Conditon to FilterInstance
$filter->addScope($conditionPrice)
->addScope(new Condition('price', Operator::GTE, 500));
// Make Collection
$collection = collect([
['price' => 9000],
['price' => 0],
['price' => 800]
]);
// Apply filter in your query
$builder = YourModel::query();
$filter->apply($collection);
// Result
dd($collection);
/*
[
['price' => 800]
]
*/
Convert to/from String
use Cetria\Laravel\Filter\Filter;
use Cetria\Laravel\Filter\Condition;
use Cetria\Laravel\Filter\Operator;
$filter = new Filter();
$conditionPrice = new Condition('price', Operator::LTE, 5000);
$filter->addScope($conditionPrice);
//result toString
$queryString = (string) $filter;
// Make Filter instance from query string
$filter = new Filter($queryString);
Available Operators
- LT => =
- LTE => <=
- EQ => =
- NEQ => !=
- GTE => >=
- GT => >
- IN => {}
- NIN => !{}
Available Logical Operators
- AND
- OR (Cannot be used for filtering in a collection instances)