PHP code example of aqjw / filterable

1. Go to this page and download the library: Download aqjw/filterable 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/ */

    

aqjw / filterable example snippets


use Aqjw\Filterable\HasFilters;

class Product
{
    use HasFilters;

Product::filters([
    \App\Filters\ByPrice::class,
    \App\Filters\BySalePrice::class,
])->get();

Product::filters([
    \App\Filters\ByPrice::class,
    'or',
    \App\Filters\BySalePrice::class,
])->get();

Product::filters([
    [
        \App\Filters\ByCategory::class,
        \App\Filters\Product\ByPrice::class,
    ],
    'or',
    [
        \App\Filters\BySubCategory::class,
        \App\Filters\BySalePrice::class,
    ],
])->get();

use Aqjw\Filterable\Filter;

class ByPrice extends Filter
{
    public function key()
    {
        // only apply the filter if 'price' is present in the request
        return 'price';
    }

    public function apply($query, $value)
    {
        $query->where('price', $value);
    }
}

use Aqjw\Filterable\Filter;

class ByCategory extends Filter
{
    public function key()
    {
        // only apply the filter if 'category' is present in the request
        return 'category';
    }

    public function isActive($request)
    {
        // always force the filter to be applied,
        //  even if 'category' is not present in the request.
        // this will be useful when we want to apply the filter by default,
        //  for example, when displaying all products in a certain category
        return true;
    }

    public function apply($query, $value)
    {
        if ($value) {
            // apply the filter based on the value of 'category' in the request
            $query->where('category', $value);
        } else {
            // if 'category' is not present in the request, default to showing products in the root category (category ID of 1)
            $query->where('category', 1);
        }
    }
}
bash
php artisan make:filter ByPrice --column=retail_price