eloquent-filter is a simple package for filtering Eloquent queries based on request query parameters with predefined methods per parameter. It allows you to easily build complex query filters for your Laravel applications.
You can install the package via composer:
composer require buibr/eloquent-filterInclude the HasFilters trait in any Eloquent model where you want to use query filters.
use BI\EloquentFilter\HasFilters;
class YourModel extends Model
{
use HasFilters;
// Other model code...
}Create a new filter class that extends QueryFilter. In this class, define methods for each query parameter you want to filter by. Each method should accept the parameter value and modify the query accordingly.
use BI\EloquentFilter\QueryFilter;
class YourModelFilter extends QueryFilter
{
public function status($value)
{
return $this->builder->where('status', $value);
}
public function category($value)
{
return $this->builder->where('category_id', $value);
}
// Add more filter methods as needed...
}In your controller, apply the filter to the query by using the filter scope. Pass an instance of your filter class as the argument.
use App\Models\YourModel;
use App\Filters\YourModelFilter;
class YourController extends Controller
{
public function index(YourModelFilter $filters)
{
$items = YourModel::filter($filters)->get();
return response()->json($items);
}
}You can now filter the query by passing parameters in the request URL:
GET /your-models?status=active&category=1
This will apply the status and category filters based on the methods defined in your YourModelFilter class.
To customize how filters are applied, simply add more methods to your filter class. Each method corresponds to a query parameter and can modify the Eloquent query as needed.
class YourModelFilter extends QueryFilter
{
public function created_at($value)
{
return $this->builder->whereDate('created_at', $value);
}
public function sort($value)
{
return $this->builder->orderBy('created_at', $value);
}
}Contributions are welcome! If you encounter any issues or have suggestions for improvements, please open an issue or submit a pull request.
This package is open-sourced software licensed under the MIT license.