Eloquent & Data Access v3

Filter for Relations

Laravel Model Filter · A Laravel package for filtering and searching models from database with ease.

Version and pages

You are reading version v3. The current documentation is v4.

Commit 4616a40d07f1 This page on GitHub

You can create a simple Relation filter by extending the base SelectFilter. In the following example we create a Tag-Filter that can be applied to all models that have a tag relation.

Thanks to hfmiguel for this example.

class TagsFilter extends SelectFilter
{
    public FilterMode $mode = FilterMode::EQUAL;

    protected string $field = 'tag_id';  /**  column of the relation */ 
    protected string $relation = 'tags';  /** relation name : where the search will be applied */

    public function title(): string
    {
        return __('Tags');
    }

    public function options(): array
    {
        return Tag::query()
            ->orderBy('name')
            ->pluck('id', 'name')
            ->toArray();
    }
    
    public function apply(Builder $query): Builder
    {
        return $query->whereHas($this->relation, function (Builder $query) {
            $query->whereIn($this->field, $this->values);
        });
    }
}

Technical consultation

A package as a building block for your application.

If architecture, integration or operations are critical, let’s discuss your application as a whole.

Discuss your project