Skip to content

Instantly share code, notes, and snippets.

@rohan-krishna
Created April 27, 2018 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohan-krishna/b023c6249674e7999cd7a3d168d86da7 to your computer and use it in GitHub Desktop.
Save rohan-krishna/b023c6249674e7999cd7a3d168d86da7 to your computer and use it in GitHub Desktop.
Laravel 5 — How to build multiple Query Filters for Eloquent Model
<?php
namespace app;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
abstract class QueryFilter
{
protected $request;
protected $builder;
public function __construct(Request $request)
{
$this->request = $request;
}
public function customArrayFilter($var)
{
return ($var !== null && $var !== false && $var !== '');
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach ($this->filters() as $name => $value) {
if (method_exists($this, $name)) {
call_user_func_array([$this, $name], array_filter([$value, 'customArrayFilter']));
}
}
return $this->builder;
}
public function filters()
{
return $this->request->all();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment