Looking to hire Laravel developers? Try LaraJobs

laravel-filters maintained by alexskoromnui

Description
Dynamic create query with filters for search
Last update
2023/01/18 13:29 (dev-master)
License
Downloads
159

Comments
comments powered by Disqus

Laravel Search Filters

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() ..)