Created
April 8, 2017 14:50
-
-
Save colindecarlo/ede5a1d7b98e406a066a7fec5cf2e782 to your computer and use it in GitHub Desktop.
Plug'n'play filter trait for filtering resources in your controllers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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