Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mykeels/laravel-filters
A laravel package that provides a composable interface for data filtering with query strings 😍
https://github.com/mykeels/laravel-filters
composable eloquent filters
Last synced: about 2 months ago
JSON representation
A laravel package that provides a composable interface for data filtering with query strings 😍
- Host: GitHub
- URL: https://github.com/mykeels/laravel-filters
- Owner: mykeels
- Created: 2018-08-05T14:47:40.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-12-03T07:09:34.000Z (about 5 years ago)
- Last Synced: 2024-09-18T01:17:57.045Z (5 months ago)
- Topics: composable, eloquent, filters
- Language: PHP
- Homepage: https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8
- Size: 101 KB
- Stars: 15
- Watchers: 2
- Forks: 7
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Laravel Filters
Imagine that ...
## Filter with Query String
This URL:
```text
/users?name=myk&age=21&company=rick-and-morty&sort_age=desc
```automatically knew to filter the DB query by responding with users that have their
- name containing `myk`
- age as `21`
- company name containing `rick-and-morty`and order the records by age in descending order, all without you having to write boilerplate code 😱.
## Load Relationships
Or that you could automatically include a relationship for a model by adding a `?with_relationship` to the URL 😍, like:
![laravel-filters](https://user-images.githubusercontent.com/11996508/43687436-08f61c1c-98cd-11e8-962b-cd32c2d3bfb3.gif)
Hold your horses 😜, I'm about to show you how.
## Setup
- Run `composer require mykeels/laravel-filters` in your terminal to pull the package in.
## Usage
- In the Model class you wish to make filterable, use the `FilterableTrait` like:
```php
builder->where('users.name', 'LIKE', "%$term%");
}
public function company($term) {
return $this->builder->whereHas('company', function ($query) use ($term) {
return $query->where('name', 'LIKE', "%$term%");
});
}
public function age($term) {
$year = Carbon::now()->subYear($age)->format('Y');
return $this->builder->where('dob', '>=', "$year-01-01")->where('dob', '<=', "$year-12-31");
}public function sort_age($type = null) {
return $this->builder->orderBy('dob', (!$type || $type == 'asc') ? 'desc' : 'asc');
}
}
```> Note how the name of each method maps to the key of each query string in `/users?name=myk&age=21&company=rick-and-morty&sort_age=desc`, and the parameters of the methods map to the values.
- Inject `UserFilters` in your controller 😍, like:
```php
get();
}
}
```That's all! 💃
Now, you can execute your app, and use variations of the query strings that your filters allow for. 🔥🔥🔥