Skip to content

Instantly share code, notes, and snippets.

@nkeena
Created February 5, 2020 04:52
Show Gist options
  • Save nkeena/7a4db103e58926060cd00ffff00ec655 to your computer and use it in GitHub Desktop.
Save nkeena/7a4db103e58926060cd00ffff00ec655 to your computer and use it in GitHub Desktop.
A simple trait that provides robust filtering by a model's attributes
<?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