Skip to content

Instantly share code, notes, and snippets.

@eduPHP
Created April 14, 2021 14:47
Show Gist options
  • Save eduPHP/963cc44af680d000bbc940ec41962c51 to your computer and use it in GitHub Desktop.
Save eduPHP/963cc44af680d000bbc940ec41962c51 to your computer and use it in GitHub Desktop.
<?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);
}
}
@eduPHP
Copy link
Author

eduPHP commented Apr 14, 2021

Exemplo de utilização

// query = https://meusite.com/sells?buyer=Eduardo&test=true

// controller
$filters = ['test', 'id', 'status', 'buyer', 'seller', 'item', 'date', 'subscription', 'coupon'];
$sells = Invoice::filtered($filters);

return $sells->paginate();

@eduPHP
Copy link
Author

eduPHP commented Apr 14, 2021

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