Download the PHP package architools/laravel-sieve without Composer
On this page you can find all versions of the php package architools/laravel-sieve. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download architools/laravel-sieve
More information about architools/laravel-sieve
Files in architools/laravel-sieve
Package laravel-sieve
Short Description Laravel Sieve is a lightweight yet powerful filtering and sorting engine for Laravel applications. It transforms HTTP query parameters into clean, maintainable Eloquent or Query Builder queries with zero boilerplate. Built to follow SOLID and DRY principles, this modular package supports dynamic filtering, custom sorting, relationship constraints, and JSON field queries. Ideal for RESTful APIs, admin panels, and data-intensive applications, it keeps your controllers slim and your queries expressive β all while embracing Laravel best practices.
License MIT
Informations about the package laravel-sieve
Introduction
Laravel Sieve is a modular, scalable filtering engine designed to keep your codebase clean, maintainable, and easy to extend. It eliminates bloated controllers and scattered if statements with a structured, composable approach to dynamic, request-driven query filtering. By isolating filter logic into well-defined, single-responsibility classes, it enforces true separation of concerns while staying fully aligned with SOLID and DRY principles.
Whether you're building RESTful APIs, admin panels, or data-intensive applications, Laravel Sieve fits right in β offering the flexibility and structure needed for modern Laravel projects:
π§± Decouple business logic with focused, single-responsibility filter classes.
π Easily extend and customize filters to meet your unique requirements.
π§ Compose complex query conditions effortlessly β even across nested relationships
βοΈ Apply multiple sorts dynamically and cleanly, directly from request input
βοΈ Seamlessly integrate into your existing Laravel codebase with minimal setup
Designed for scalability, and developer satisfaction.
Requirements
- PHP >= 8.2
- Laravel >= 11.0
Installation
- Install the package via Composer:
Table of Contents
- Getting Started
- Creating a Custom Utilities Service
- Defining Filters
- Reusable Filter Classes
- Defining Sorts
- Using the Utilities Service
- Building the Query
- Components
- Utilities Service
- Criteria
- Conditions
- Joins
- Sorts
- Contact & Feedback
Getting Started
Create a Custom Utilities Service
To begin, define your own service class that extends the base UtilitiesService
class:
Defining Filters
Define available filters inside the filters()
method of your service class. Each filter is a key-value
pair where:
- The key represents the query parameter name.
- The value is either a method name to handle the filter implementation or a
Filter
instance.
Each filter method receives two arguments:
Criteria $criteria
: The criteria instance for appending conditions & joins.
mixed $value
: The filter value from the request.
π For more on how Criteria works, see the Criteria section
π Tip: Always validate filter values using Form Requests, or another approach you prefer.
π Explore Available Conditions β
Applying Joins in Filters
Need to use Join's in filters? No problem β just append them inside your filter method:
You can even attach conditions directly to the join:
β Best Practice: To avoid overwriting joins when reusing the same one in multiple filters, always check if it already exists:
π Important: Appending a join with an existing name will overwrite the previous one.
Example with Multiple Filters Using Joins
π Explore Available Joins β
Reusable Filter Classes
You can reuse common filters across services by implementing the Filter
interface:
To apply a reusable filter class in your service, simply register it in the filters()
method:
π Note: If you need to reuse the same filter logic but apply it to different columns
, consider modifying the
filter class to accept a column name and use it dynamically in the apply()
method.
You can reuse it in other services too:
π Important:
π Make sure your filter class implements the Filter
interface and its apply()
method.
Defining Sorts
Define available sorts inside the sorts()
method of your service class. Each sort is a key-value
pair where:
- The key represents the sort name.
- The value is either:
- The name of a
method
that returns aBaseSort
instance. - A string representing a
column name
oralias
, which will be used directly for sorting
- The name of a
π Note: Sorts query parameters are expected in the following format:
- The
direction
key is optional (ASC
is default). - The sorts key can be customized by overriding the
$sortsKey
property:
π Explore Available Sorts β
Using the Utilities Service
Inject the service into your controller and apply filters and sorts:
Building the Query
Utilize the Criteria
object to modify thebuilder
instance
β
applyOnBuilder()
can be used anywhere you're building queriesβnot just limited repositories.
Components
Utilities Service
The UtilitiesService
class is an abstract base class that provides a structured way to handle filtering and sorting in
your Laravel applications. It acts as a bridge between HTTP requests and the Criteria class, making it easy to implement
filtering and sorting functionality in your services.
Purpose
The UtilitiesService
class serves as a foundation for building filterable and sortable services. It allows you to:
- Automatically process filter and sort parameters from HTTP requests.
- Define available filters and sorts for your service.
- Apply filters and sorts to your queries in a consistent way.
Available Methods
getCriteria(): Criteria
- Returns: The current Criteria instance
fresh(): UtilitiesService
Initializes a fresh Criteria
instance and resets the internal state of the service.
- Returns: The current service instance
applyFilters(): UtilitiesService
Applies all valid filters from the request to the Criteria instance.
- Returns: The current service instance
applySorts(): UtilitiesService
Applies all valid sorts from the request to the Criteria instance.
- Returns: The current service instance
Protected Methods to Override
filters(): array
Define the available filters for your service.
- Returns: An associative array where each
key
is the filter name, and thevalue
is either afilter instance
or the name of amethod name
that implements the filter.
sorts(): array
Define the available sorts for your service.
- Returns: An associative array where each key is the sort name used in requests, and the value is either:
field/column
name to sort by directly.method name
that returns a BaseSort instance for custom logic.
Usage Examples
Basic Implementation
Complex Implementation
Best Practices
- Create dedicated filter classes for complex or frequently reused filters.
- Always validate filter and sort parameters to ensure data integrity.
- Be mindful of security risks when handling user-provided input.
- Keep filtering and sorting logic clean, focused, and limited to a single responsibility.
Criteria
The Criteria
class is the main orchestrator of the Laravel Sieve package. It manages and applies joins, conditions,
and sorts to your query builder in a structured and organized way.
Purpose
The Criteria class serves as a container and manager for all query modifications. It allows you to:
- Build complex queries by combining multiple conditions, joins, and sorts
- Maintain a clean and organized query building process
- Apply all modifications to your query builder in the correct order
- Manage the relationships between different query components
Available Methods
appendJoin(BaseJoin $join, int $sort = 100): Criteria
Adds a join to the criteria with an optional sort order.
$join
: The join instance to add$sort
: The order in which the join should be applied (lower numbers are applied first). Defaults to 100- Returns: same
Criteria
instance
appendSort(BaseSort $sort): Criteria
Adds a sort to the criteria.
$sort
: The sort instance to add- Returns: same
Criteria
instance
removeJoinIfExists(string $joinName): Criteria
Removes a join from the criteria if it exists.
$joinName
: The name of the join to remove- Returns: same
Criteria
instance
joinExists(string $joinName): bool
Checks if a join exists in the criteria.
$joinName
: The name of the join to check- Returns:
true
if the join exists,false
otherwise
appendCondition(BaseCondition $condition): Criteria
Adds a condition to the criteria.
$condition
: The condition instance to add- Returns: same
Criteria
instance
applyOnBuilder(Builder $builder): Builder
Applies all joins, conditions, and sorts to the query builder in the correct order.
$builder
: The query builder instance to modify- Returns: The modified query builder
Example
Conditions
- Basic Conditions
- JSON Conditions
- Aggregation Conditions
- Group Conditions
- Special Conditions
Basic Conditions
Condition
Purpose: The fundamental building block for creating WHERE clauses in your queries. It handles basic comparison
operations between a field
and a value
.
Parameters:
string $field
: The database column name to apply the condition onstring $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,LIKE
,NOT LIKE
)mixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
ColumnCondition
Purpose: Used when you need to compare two columns
in the same table or across joined tables.
Parameters:
string $field
: The database column name to apply the condition onstring $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,LIKE
,NOT LIKE
)mixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
JSON Conditions
JsonContainCondition
Parameters:
string $field
: The database column name to apply the condition onmixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.bool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
Purpose: Checks if a JSON array contains a specific value. Useful for querying JSON columns that store arrays.
Parameters:
$field
: The database column name to apply the condition on$value
: The value to compare against$boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
JsonContainsKeyCondition
Purpose: Verifies if a JSON object contains a specific key. Useful for checking the existence of properties in JSON data.
Parameters:
string $field
: The database column name to apply the condition onstring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.bool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
Example:
JsonLengthCondition
Purpose: Compares the length of a JSON array. Useful for filtering based on array size.
Parameters:
string $field
: The database column name to apply the condition onstring $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,)mixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
JsonOverlapCondition
Purpose: Checks if two JSON arrays have any elements in common. Useful for finding records with matching array elements.
Parameters:
string $field
: The database column name to apply the condition onmixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults to `AND.bool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
Example:
Aggregation Conditions
AggregationCondition
Purpose: Applies conditions on aggregated values (COUNT, SUM, AVG, etc.). Essential for filtering based on grouped data.
Parameters:
string $field
: The database column name to apply the condition onstring $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,LIKE
,NOT LIKE
)mixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
Group Conditions
GroupConditions
Purpose: Groups multiple conditions together with a logical operator (AND
/OR
). Enables complex query
composition.
Parameters:
BaseCondition[] $conditions
: An array of condition instances to be grouped together.string $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
Note
The
GroupConditions
class does not support mixing different condition types. Specifically, you cannot combineAggregationCondition
instances with standard (non-aggregation)Condition
instances in the same group.If mixed condition types are provided, a
MixedGroupConditionException
will be thrown to enforce consistency and prevent ambiguous behavior.
Special Conditions
BetweenCondition
Purpose: Creates a BETWEEN
clause for range queries. Useful for filtering values within a specific range.
Parameters:
string $field
: The database column name to apply the condition onarray $values
: An array containing exactly two elements, representing the lower and upper bounds.string $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.bool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
.
Example:
Note
The
BetweenCondition
requires the value to be an array containing exactly two elements β representing the lower and upper bounds of the range for aWHERE BETWEEN
comparison.If the provided array does not contain exactly two elements, an
InvalidArgumentException
will be thrown to ensure proper condition formatting.
DateCondition
Purpose: Specialized condition for date comparisons. Handles date formatting and comparison.
Parameters:
string $field
: The database column name to apply the condition onstring $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,LIKE
,NOT LIKE
)mixed $value
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults to ' and'.
Example:
InCondition
Purpose: Creates an IN clause for checking if a value exists in a set of values.
Parameters:
string $field
: The database column name to apply the condition onarray $values
: The value to compare againststring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.bool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
Example:
NullCondition
Purpose: Checks if a field is NULL or NOT NULL. Useful for filtering records based on the presence/absence of data.
Parameters:
string $field
: The database column name to apply the condition onstring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditionsbool $not
: Indicates whether to negate the condition (true
for NOT logic). Defaults tofalse
Example:
RawCondition
Purpose: Allows direct SQL conditions when complex queries are needed. Use with caution and proper parameter binding.
Parameters:
string $expression
: The raw SQL expression to be used as a condition.array $bindings
: The values to bind to the placeholders within the raw SQL expression. Defaults to an empty arraystring $boolean
: The logical operator (AND
orOR
) to use when combining with other conditions. Defaults toAND
.
Example:
π Important: Use parameter binding (?) with RawCondition to prevent SQL injection.
WhenCondition
Purpose: Conditionally applies another condition based on a boolean verification. Useful for dynamic query building.
Parameters:
bool $verification
: A boolean flag that determines whether the condition should be applied.BaseCondition $condition
: The condition to apply if the verification passes.
Example:
Best Practices
- Type Safety: Always use proper type hints and validate input values before creating conditions.
- JSON Operations: Ensure your database supports JSON operations before using JSON-related conditions.
- Performance: Consider the impact of complex conditions and nested groups on query performance.
- Condition Organization:
- Group related conditions together
- Use
GroupConditions
for complex logical combinations - Consider the order of conditions for optimal query performance
Joins
The Laravel Sieve package provides two types of joins to help you build complex queries with proper table relationships.
Join
Purpose: Creates a standard SQL JOIN clause with conditions. This is the most commonly used join type, allowing you to specify the join conditions and add additional conditions to the join clause.
Parameters:
string $table
: The table to join with.array $first
: The first column in the join condition.string $operator
: The comparison operator (=
,!=
,<>
,>
,<
,>=
,<=
,LIKE
,NOT LIKE
).string $second
: The second column in the join condition.string $type
: The type of join to perform (inner
,left
,right
). Defaults toinner
.string|null $name
: Optional name for the join. If not provided, the table name is used.
Available Methods
appendCondition(BaseCondition $condition): Join
- Adds a condition to the join clause
- Returns the join instance for method chaining
apply(Builder $builder): void
- Applies the join to the query builder
- Internal method used by the package
Example:
ClosureJoin
Purpose: Creates a join using a closure, allowing for more complex join conditions and logic.
Useful when you need to build dynamic or complex join conditions that can't be expressed with simple column comparisons.
Parameters:
string $table
: The table to join withClosure $closure
: A closure that receives the join query builder and defines the join conditionsstring $type
: The type of join to perform (inner
,left
,right
). Defaults toinner
.string|null $name
: Optional name for the join. If not provided, the table name is used
Public Methods:
apply(Builder $builder): void
- Applies the join to the query builder
- Internal method used by the package
Example:
Note
An
InvalidJoinTypeException
will be thrown if an unsupported join type is provided.
Best Practices for Joins
Join Naming and Execution Order
When working with joins, it's important to assign clear and descriptive namesβespecially when joining the same table multiple times or referencing joins later in your logic.
Named Joins: If a join with the same name already exists, it will be overwritten.
Execution Order: You can control the order in which joins are applied using the appendJoin(BaseJoin $join, int $ order = 100)
method. Joins with lower order values are executed first.
Using named and ordered joins helps maintain predictable and maintainable query structures, particularly in complex filtering scenarios.
Sorts
The Laravel Sieve package provides two types of sorts to help you order your query results.
Sort
Purpose: Creates a standard ORDER BY
clause for sorting query results. This is the most commonly used sort type,
allowing you to sort by a specific column in ascending or descending order.
Parameters:
string $field
: The column name to sort bystring $direction
: The sort direction (ASC
orDESC
). Defaults toASC
.
Available Methods:
apply(Builder $builder): void
- Applies the sort to the query builder
- Internal method used by the package
Example:
RawSort
Purpose: Creates a raw ORDER BY
clause for complex sorting requirements. Useful when you need to use SQL
expressions, functions, or complex sorting logic that can't be achieved with simple column sorting.
Parameters:
string $expression
: The raw SQL expression for sortingstring $direction
: The sort direction (ASC
orDESC
). Defaults toASC
.array $bindings
: Array of values to bind to the expression. Defaults to empty array
Available Methods:
apply(Builder $builder): void
- Applies the raw sort to the query builder
- Internal method used by the package
Example:
πImportant: Always use parameter binding with
RawSort
Best Practices for Sorts
Raw Sorts Usage:
- Custom SQL expressions
- Database functions in sorting
- Complex conditional sorting
π¬ Contact and Feedback
We welcome your feedback and contributions!
- π Bug Reports: Open an issue
- π Feature Requests: Submit a feature request
- π¬ General Feedback or Questions: Feel free to reach out via [email protected]
All versions of laravel-sieve with dependencies
illuminate/database Version ^11.0 || ^12.0
illuminate/http Version ^11.0 || ^12.0
illuminate/support Version ^11.0 || ^12.0