PHP code example of stepovenko / eloquent-filter-sort-pagination

1. Go to this page and download the library: Download stepovenko/eloquent-filter-sort-pagination 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/ */

    

stepovenko / eloquent-filter-sort-pagination example snippets




namespace App\Http\Controllers;

use App\Filters\ProductFilter;
use App\Models\Product;

class ProductController extends Controller
{
    public function index(ProductFilter $productFilter)
    {
        return Product::paginationFilter($productFilter);
    }
}



namespace App\Filters;

use Stepovenko\FilterableAndSortable\Filters\QueryFilter;

class ProductFilter extends QueryFilters
{
    public function getFilterableFields(): array
    {
        return ['name'];
    }

    public function getSortableFields(): array
    {
        return ['price'];
    }

    public function name($term)
    {
        $this->builder->where('products.name', 'LIKE', "%$term%");
    }
}

$products = Product::filter($productFilter)->paginationFilter();

$products = Product::filter($productFilter)->get();

$products = Product::filter($productFilter)->pagination();

 arisan make:filter Product



namespace App\Filters;

use Stepovenko\FilterableAndSortable\Filters\QueryFilter;

class ProductFilter extends QueryFilters
{
    protected string $defaultSort = 'price-asc';
    protected int $maxPerPage = 100;
    protected int $defaultPerPage = 15;

    public function getSortableFields(): array
    {
        return ['category_name'];
    }

    // if you saved price as string
    public function getSortableFieldsLikeNumber(): array
    {
        return ['price'];
    }

    // override standard sort prefix sort_
    public function sort_categories_name($term)
    {
        $this->builder->where('category.name', 'LIKE', "%$term%");
    }
}



namespace App\Http\Controllers;

use App\Filters\ProductFilter;
use App\Models\Product;

class ProductController extends Controller
{

    public function index(ProductFilter $productFilter)
    {
        // internal public methods
        $productFilter->setDefaultSort('price-desc');
        $perPega = $productFilter->getPerPage();
        $request = $productFilter->getRequest();
        $builder = $productFilter->getBuilder();
    }

}
 artisan vendor:publish --tag=filterable-and-sortable-config