-
-
Save minedun6/f99966b3caf4bff29eba17992b65b392 to your computer and use it in GitHub Desktop.
Abstract Layer for Query Filters in Laravel
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\Filters\Query; | |
trait Filterable | |
{ | |
/** | |
* Apply Filters on the Eloquent Model | |
* | |
* @param $query | |
* @param QueryFilter $filters | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
public function scopeFilter($query, QueryFilter $filters) | |
{ | |
return $filters->apply($query); | |
} | |
} |
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\Filters\Query; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Http\Request; | |
abstract class QueryFilter | |
{ | |
protected $request; | |
protected $builder; | |
/** | |
* QueryFilter constructor. | |
* | |
* @param Request $request | |
*/ | |
public function __construct(Request $request) | |
{ | |
$this->request = $request; | |
} | |
/** | |
* Apply filters in request on resource if they are implemented in the resourceFilters class | |
* | |
* @param Builder $builder | |
* @return Builder | |
*/ | |
public function apply(Builder $builder) | |
{ | |
$this->builder = $builder; | |
foreach ($this->filters() as $name => $value) { | |
if (! method_exists($this, $name)) { | |
continue; | |
} | |
if(strlen($value)) { | |
$this->$name($value); | |
} else { | |
$this->$name(); | |
} | |
} | |
return $this->builder; | |
} | |
/** | |
* Get filters from the request | |
* | |
* @return array | |
*/ | |
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