Laravel Model Filter offers a simple way to filter and search eloquent models by array parameters and query strings.
Here's a simple example to illustrate exactly how this package works. Given the following filter, you can generate with the provided make:filter
command:
namespace App\Models\Filters;
use Lacodix\LaravelModelFilter\Filters\DateFilter;
class CreatedAfterFilter extends DateFilter
{
public FilterMode $mode = FilterMode::GREATER_OR_EQUAL;
protected string $field = 'created_at';
}
You can apply the CreatedAfterFilter
on a model like the following example:
namespace App\Models;
use App\Models\Filters\CreatedAfterFilter;
use Illuminate\Database\Eloquent\Model;
use Lacodix\LaravelModelFilter\Traits\HasFilters;
class Post extends Model
{
use HasFilters;
protected array $filters = [
CreatedAfterFilter::class,
];
}
You can then trigger the filter either programmatically or via query string:
Post::filter(['created_after_filter' => '2023-01-01'])->get();
// Multiple filters
Post::filter([
'created_after_filter' => '2023-01-01',
'published_filter' => true,
])->get();
// Or by query string: /posts?created_after_filter=2023-01-01
Post::filterByQueryString()->get();
This package includes many features related to filtering models, such as:
- Group filtering
- Filter validation
- Sorting
- Searching
- Date filter type
- String filter type
- Select filter type
- Numeric filter type
- Boolean filter type
- Trashed filter type
- Filtering on relations
- And more
To get started with this package, check out the official documentation; the source code is also on GitHub at lacodix/laravel-model-filter.