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 filtersPost::filter([ 'created_after_filter' => '2023-01-01', 'published_filter' => true,])->get(); // Or by query string: /posts?created_after_filter=2023-01-01Post::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
0 comments:
Post a Comment
Thanks