Skip to content

Instantly share code, notes, and snippets.

@colindecarlo
Created April 8, 2017 14:50
Show Gist options
  • Save colindecarlo/ede5a1d7b98e406a066a7fec5cf2e782 to your computer and use it in GitHub Desktop.
Save colindecarlo/ede5a1d7b98e406a066a7fec5cf2e782 to your computer and use it in GitHub Desktop.
Plug'n'play filter trait for filtering resources in your controllers
<?php
namespace App\Http;
/**
* ?filter[foo]=bar&filter[qux]=baz
*/
trait FiltersRequests
{
private function filter($query)
{
foreach (request('filter') as $attribute => $value) {
if (! $filterMethod = $this->toFilter($query, $attribute)) {
continue;
}
$this->$filterMethod($query, $value, $attribute);
}
}
private function toFilter($query, $attribute) {
$filterMethod = sprintf('filter%s', studly_case($attribute));
if ($this->hasFilter($filterMethod)) {
return $filterMethod;
}
if ($this->hasScopeFor($query->getModel(), $attribute)) {
return 'filterUsingScope';
}
return null;
}
private function hasScopeFor($model, $attribute) {
return method_exists($model, sprintf('scope%s', ucfirst($attribute)));
}
private function filterUsingScope($query, $value, $attribute)
{
$scope = sprintf('scope%s', ucfirst($attribute));
return $query->getModel()->$scope($query, $value);
}
private function hasFilter($filterMethod)
{
return method_exists($this, $filterMethod);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment