alexskoromnui/laravel-filters

Dynamic create query with filters for search

1.0.0 2021-04-30 10:10 UTC

This package is not auto-updated.

Last update: 2025-03-29 01:59:55 UTC


README

Package for dynamic adding new search filters.

Install package

composer require alexskoromnui/laravel-filters

Usage

For demonstration i will use ExampleModel class which locate in app folder, filters for this model will locate in Filters folder.

Step 1

Your search model should implement SearchableModel interface from this package which has one method getFiltersNamespace() in which you should specify namespace of filters for this model.


namespace App;

use Illuminate\Database\Eloquent\Model;

class ExampleModel extends Model implements SearchableModel
{
	    public function getFiltersNamespace(): string
    {
        return 'App\Filters';
    }
}

Step 2

Let's imagine that ExampleModel has name property, and in request we have ?name=TEST

Step 3

You should create filter and implement Filter interface from this package which has one method apply(Builder $builder, $value) in which you should write your query.

namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;
use Skoromnui\Filters\Filter;

class Name implements Filter
{
    public function apply(Builder $builder, $value)
    {
        return $builder->where('name', 'like', '%' . $value . '%');
    }
}

Step 4

After all this steps your Controller or Service will look like this:

use App\Http\Controllers\Controller;
use App\ExampleModel;
use Illuminate\Http\Request;
use Skoromnui\Filters\Service\SearchService;

class ExampleController extends Controller
{
    public function search(Request $request, SearchService $searchService)
    {
        $query = $searchService->buildQuery($request, new ExampleModel());
        
        $result = $query->get();

        return response()->json($result);
    }
}

Step 5

SearchService from this package is engaged in build query, after that you can use any methods like (get(), paginate(), limit(), offset(), count() ..)