Created
April 27, 2018 04:36
-
-
Save rohan-krishna/b023c6249674e7999cd7a3d168d86da7 to your computer and use it in GitHub Desktop.
Laravel 5 — How to build multiple Query Filters for Eloquent Model
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; | |
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