Created
April 14, 2021 14:47
-
-
Save eduPHP/963cc44af680d000bbc940ec41962c51 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
use Illuminate\Support\Str; | |
trait Filterable | |
{ | |
public function scopeFiltered($query, array $allowed) | |
{ | |
foreach ($allowed as $key => $property) { | |
if (is_numeric($key)) { | |
$this->filter($query, $property); | |
} else { | |
$this->filter($query, $property, $key); | |
} | |
} | |
return $query; | |
} | |
private function filter($query, $property, $parameter = null) | |
{ | |
$search = $parameter ?: $property; | |
if(!$value = request($search)) { | |
return $query; | |
} | |
$searchMethod = $this->getMethod($search); | |
$filterClass = $this->filterClass($query); | |
if ($filterClass && method_exists($filterClass, $searchMethod)) { | |
return $filterClass->{$searchMethod}($value); | |
} | |
return $query->where($search, $value); | |
} | |
private function filterClass($query) | |
{ | |
$className = class_basename($this); | |
$filterName = "App\\Filters\\{$className}Filter"; | |
if (!class_exists($filterName)) { | |
return null; | |
} | |
return new $filterName($query); | |
} | |
private function getMethod($search) | |
{ | |
$search = str_replace(['.', '-'], '_', $search); | |
return Str::camel($search); | |
} | |
} |
Exemplo de filtro customizado:
// App\Filters\InvoiceFilter
namespace App\Filters;
use App\Invoice;
use Carbon\Carbon;
class InvoiceFilter extends Filter
{
public function buyer($value)
{
$this->query->whereHas('buyer', function ($buyer) use ($value) {
$buyer->where('name', 'like', "%{$value}%")->orWhere('email', 'like', "%{$value}%");
});
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exemplo de utilização