For filtering and sorting in eloquent
stepovenko/eloquent-filter-sort-pagination is a Laravel package for for filtering and sorting in eloquent.
It currently has 1 GitHub stars and 31 downloads on Packagist (latest version 1.0.9).
Install it with composer require stepovenko/eloquent-filter-sort-pagination.
Discover more Laravel packages by stepovenko
or browse all Laravel packages to compare alternatives.
Last updated
https://example.com?sort=price-desc&name=iphone<?php
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);
}
}
<?php
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%");
}
}
Or you can use
$products = Product::filter($productFilter)->paginationFilter();
$products = Product::filter($productFilter)->get();
$products = Product::filter($productFilter)->pagination();
Console command to create a filter
php arisan make:filter Product
<?php
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%");
}
}
<?php
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();
}
}
config publication
php artisan vendor:publish --tag=filterable-and-sortable-config