Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abdolrhman/6d024f740a260ea05dad150f567ba504 to your computer and use it in GitHub Desktop.
Save abdolrhman/6d024f740a260ea05dad150f567ba504 to your computer and use it in GitHub Desktop.
Filter methods
That's always been my approach, at least. If I needed to filter results, I would have a chainable method on my repository that would apply a relatively simple key-value filter. This trait is ripped directly from a current project:
trait FilterableTrait
{
protected $validFilterableFields = [];
protected $filters = [];
protected function addFilter($field, $value)
{
if(!in_array($field, $this->validFilterableFields)) {
return false;
}
$filterMethod = 'filterBy' . camel_case($field);
if( method_exists( $this, $filterMethod ) ) {
$this->$filterMethod($value);
} else {
$this->filters[$field] = $value;
}
return true;
}
protected function applyFiltersToQuery($query)
{
foreach($this->filters as $field => $value) {
$query->where($field, $value);
}
return $query;
}
}
Typically, I'd add it to a repository and use that to do the filtering:
//not ripped from a current project, sadly :'(
class EloquentAvengersRepository extends EloquentRepository implements AvengersRepository
{
use FilterableTrait;
$this->validFilterableFields = ['is_genius', 'owns_hammer', 'loves_freedom', 'unpopular_when_angry'];
public function filterBy($field, $value)
{
$this->addFilter($field, $value);
return $this;
}
public function all()
{
return $this->applyFiltersToQuery( $this->query() )->paginate(10);
}
}
So now I can use the repository like so:
$this->avengersRepo->filterBy($foo, $bar)->all();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment