indexzer0/eloquent-filtering
Define allowed filters on your Eloquent models and apply them from simple arrays or request data—no custom query logic. Supports complex, type-based filtering for APIs and dashboards on Laravel 10+ / PHP 8.2+.
You can specify that Filter::field(), Filter::relation(), Filter::morphRelation(), Filter::morphType() and Filter::custom() filters must be required.
RequiredFilterException is thrown.RequiredFilterException extends Laravels ValidationException.
public function allowedFilters(): AllowedFilterList
{
return Filter::only(
/*
* Field
*/
Filter::field('name', [FilterType::LIKE])->required(),
/*
* Relation
*/
Filter::relation('books', [FilterType::HAS],
Filter::only(
Filter::field('title', [FilterType::LIKE])->required()
)
)->required(),
/*
* Morph Relation
*/
Filter::morphRelation('imageable', [FilterType::HAS_MORPH],
/*
* Morph Type
*/
Filter::morphType(Article::class,
Filter::only(
Filter::field('title', [FilterType::LIKE])->required()
)
)->required()
)->required(),
/*
* Custom
*/
Filter::custom('$latest')->required()
);
}
Model::filter([]);
// RequiredFilterException errors
[
'name' => [
'Name filter is required.',
],
'books' => [
'Books filter is required.',
],
'books.title' => [
'Title filter is required.',
],
'imageable' => [
'Imageable filter is required.',
],
'imageable.articles' => [
'Articles filter is required.',
],
'imageable.articles.title' => [
'Title filter is required.',
],
'$latest' => [
'$latest filter is required.',
],
]
scoped parameter to true to achieve this.public function allowedFilters(): AllowedFilterList
{
return Filter::only(
Filter::relation('books', [FilterType::HAS],
Filter::only(
Filter::field('title', [FilterType::LIKE])
->required(scoped: true)
)
),
);
}
Model::filter([]);
// 'books' relation filter not used
// RequiredFilterException not thrown.
Model::filter([
[
'target' => 'books',
'type' => '$has',
]
]);
// 'books' relation filter used
// RequiredFilterException errors
[
'books.title' => [
'Title filter is required.',
],
]
How can I help you explore Laravel packages today?