Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active December 27, 2023 10:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/ef19a4ea45770a285e4e9f85c1651ad1 to your computer and use it in GitHub Desktop.
Save afiqiqmal/ef19a4ea45770a285e4e9f85c1651ad1 to your computer and use it in GitHub Desktop.
Laravel Query Filter using Pipeline

Donate

Laravel Query Filter using Pipeline

Basically, with a pipeline we can pass an object through a stack of tasks and get the result via a callback.

Refer Here -> https://laravel.com/api/7.x/Illuminate/Pipeline/Pipeline.html

The method handle used to execute the task receives two parameters, the first is the object that we passed to our pipeline, the second is a closure, where the object will be sent to run the next task.

Before pipeline

After Pipeline

<?php
class AppUser extends Authenticatable
{
use Filterable;
}
<?php
....
public function getData()
{
AppUser::filter([
MobilePhoneFilter::class,
'\App\Models\Filters\OtherFilter:created_at' // if want to pass attribute to the third params like middleware do
])->get();
}
....
<?php
class BaseFilter
{
private $request;
public function __construct($request = null)
{
$this->request = json_decode(json_encode($request)) ?? request();
}
public function getRequest()
{
return $this->request;
}
}
<?php
use Illuminate\Pipeline\Pipeline;
trait Filterable
{
public function scopeFilter($query, array $through)
{
return app(Pipeline::class)
->send($query)
->through($through)
->thenReturn();
}
}
<?php
class MobilePhoneFilter extends BaseFilter
{
public function handle($query, $next)
{
$request = $this->getRequest();
if (isset($request->mobile_phone)) {
$query->where('mobile_phone', 'LIKE', "%$request->mobile_phone%");
}
return $next($query);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment