The Sieve is a Laravel framework package to create query filters much more easy and clean.
install package with Composer
composer require masoudi/laravel-sieve
Create a new filter by running the following artisan command
php artisan make:filter IndexPostsFilter
Filter will be create at app/Http/Filters path.
use Masoudi\Sieve\Filter;
class IndexPostsFilter extends Filter
{
/**
* Apply conditions on model
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Query\Builder $builder
*
* @return \Illuminate\Database\Query\Builder
*/
function filter(Request $request, Builder $builder)
{
$builder = $builder->where("is_active", true)
->where('published', true)
->whereHas('comments', function($query){
$query->where('slug', '=', $request->slug);
});
return $builder;
}
}
Use Filterable
trait at model;
use Masoudi\Sieve\Filterable;
class Post extends Model {
use Filterable;
}
Post::filter(new IndexPostsFilter)->get();