Mappings

Sometimes you might want to use more meaningful values for your query string keys, and these values could be different from the values you actually need for filtration, this is where the $mappings array role comes.

You can define your values mappings in the $mappings array , and then resolve the values back using the resolveValue method inside your filter class.

The resolveValue method resolves the value out of the $mappings array or returns null if the value is not found.

Pay attention to the null because it can sometimes cause unexpected behavior when filtering or ordering your records.

Example:
Let's assume you would like to order a list of products by their price, and you don't want to have:
..?price=asc or ..?price=desc in your URL,
instead you would like to have something like:
..?price=lowest or ..?price=highest

Passing a filters array to filter:

Use this when you want to apply a filter to a single query:

publicfunctionindex(Request$request){returnProduct::filter($request,[// "color" here is the key to be used in the query string// e.g. https://example.com/products?color=red"color"=>\App\Http\Filters\Product\ColorFilter::class, ])->get();}

In the above example the filter will look for the value of the key color in the query string for this query only, and pass it to the filter method inside the filter class where you have put your filtration logic.

Defining model filters:

The Filterable trait providers a filters method that should return an array of "keys" and "filters" to be applied to the model every time the filter method is called.

<?phpnamespaceApp;useAldemeery\Sieve\Concerns\Filterable;useIlluminate\Database\Eloquent\Model;classProductextendsModel{useFilterable;/** * List of individual filters to be used by the model. * * @return array*/protectedfunctionfilters() {return ['color'=>\App\Http\Filters\Product\ColorFilter::class, ]; }}

Now everytime you call the filter method on the model, you will have the ColorFilter applied on your query without passing any external arguments.

publicfunctionindex(Request$request){// The ColorFilter is automatically applied.returnProduct::filter($request)->get();}

Filter Bags

Sometimes you might have a large list of filters that is making your model look messy, or you might want to group a list of filters so you can share them between different models. This is when you want to have a filter bag.

A filter bag is a class that extends Aldemeery\Sieve\FilterBag and contains an array of filters that are always applied together.

Again you can manually create your filter bag class and place it wherever you like, or use the make:filter-bag command to create a filter bag class that is placed inside the app\Http\Filters directory.