aedart/athenaeum-filters

Search filter utilities, based on http query parameters

6.2.1 2022-05-28 13:06 UTC

This package is auto-updated.

Last update: 2022-05-28 13:08:29 UTC


README

Offers a way to create search and constraint query filters, based on received http query parameters, for your Laravel application.

Example

Your custom filters builder

By extending the BaseBuilder abstraction, you can encapsulate a custom filters builder. Whenever a http query parameter is matched, a corresponding "processor" is invoked, which is responsible for creating one or more query filters.

namespace Acme\Filters;

use Aedart\Filters\BaseBuilder;
use Acme\Filters\Processors\MySearchProcessor;
use Acme\Filters\Processors\TextProcessor;
use Acme\Filters\Processors\DateProcessor;
use Acme\Filters\Processors\SortProcessor;

class UserFilterBuilder extends BaseBuilder
{
    public function processors(): array
    {
        // Key = http query parameter, value = parameter processor...
        return [
            'search' => MySearchProcessor::make(),
            
            'name' => TextProcessor::make(),
            
            'created_at' => DateProcessor::make(),
            
            'sort' => SortProcessor::make()
                ->force(),
            
            // ...etc
        ];
    }
}

In your request

To use your custom filters builder, create a new instance in your request, e.g. in the after validation hook.

namespace Acme\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Aedart\Contracts\Filters\BuiltFiltersMap;
use Acme\Filters\UserFilterBuilder;

class ListUsersRequest exends FormRequest
{
    public ?BuiltFiltersMap $filters = null;

    public function after(Validator $validator)
    {        
        // Using your custom filters builder, build filters
        // for this request...
        $this->filters = UserFilterBuilder::make($this)
            ->build();
    }

    // ... remaining not shown ...
}

In your controller

Lastly, apply the filters directly on your model.

use App\Http\Controllers\Controller;
use App\Models\User;
use Acme\Requests\ListUsersRequest;

class UsersController extends Controller
{
    public function index(ListUsersRequest $request)
    {
        // Apply all requested filters...
        return User::applyFilters($request->filters->all())
            ->paginate(10);
        );
    }
}

Official Documentation

Please read the official documentation for additional information.

The mono repository is located at github.com/aedart/athenaeum

Versioning

This package follows Semantic Versioning 2.0.0

License

BSD-3-Clause, Read the LICENSE file included in this package