Created
February 5, 2020 04:52
-
-
Save nkeena/7a4db103e58926060cd00ffff00ec655 to your computer and use it in GitHub Desktop.
A simple trait that provides robust filtering by a model's attributes
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\Traits; | |
use Illuminate\Support\Str; | |
trait HasFilters | |
{ | |
public function scopeFilter($query, $filters = []) | |
{ | |
if ($filters <> []) { | |
foreach ($filters as $key => $value) { | |
$methodName = 'scope' . ucfirst($key); | |
if (method_exists($this, $methodName)) { | |
$this->{$methodName}($query, $value); | |
} else { | |
$query->when(Str::endsWith($key, ':contains'), function ($q) use ($key, $value) { | |
$q->where($this->table . '.' . str_replace(':contains', '', $key), 'like', "%$value%"); | |
}) | |
->when(Str::endsWith($key, ':missing'), function ($q) use ($key, $value) { | |
$q->where($this->table . '.' . str_replace(':missing', '', $key), 'not like', "%$value%"); | |
}) | |
->when(Str::endsWith($key, ':equals'), function ($q) use ($key, $value) { | |
$q->where($this->table . '.' . str_replace(':equals', '', $key), '=', $value); | |
}) | |
->when(Str::endsWith($key, ':notequal'), function ($q) use ($key, $value) { | |
$q->where($this->table . '.' . str_replace(':notequal', '', $key), '<>', $value); | |
}) | |
->when(Str::endsWith($key, ':known'), function ($q) use ($key) { | |
$q->whereNotNull($this->table . '.' . str_replace(':known', '', $key)); | |
}) | |
->when(Str::endsWith($key, ':unknown'), function ($q) use ($key) { | |
$q->whereNull($this->table . '.' . str_replace(':unknown', '', $key)); | |
}); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment