Eloquent & Datenzugriff v4

Filter for Relations

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

Version und Seitenübersicht
Commit 576ced40f4a8 Diese Seite auf GitHub

In the simple cases, you can use the RunsOnRelation trait to run any existing filter on a relation.

However, if you have more complex requirements, like nested relations, you can manually use Laravel's whereHas method or use the RunsOnRelation trait with a dot-notated relation name.

For most cases, just using the trait is enough.

class PostTitleFilter extends StringFilter
{
    use RunsOnRelation;

    protected string $relation = 'post';
    protected string $field = 'title';
}

You can also filter through nested relations by using a dot-notated relation name:

class AuthorPostTitleFilter extends StringFilter
{
    use RunsOnRelation;

    protected string $relation = 'author.posts';
    protected string $field = 'title';
}

This will automatically wrap the logic in whereHas('author.posts', ...) and correctly qualify the title column using the posts table name.

If you need more control, such as adding additional constraints to the whereHas query, you can manually override the applyFilter method while still using the trait:

class CustomRelationFilter extends StringFilter
{
    use RunsOnRelation;

    protected string $relation = 'posts';
    protected string $field = 'title';

    public function applyFilter(Builder $query): Builder
    {
        // Add custom constraints inside the whereHas closure
        $query->where('published', true);

        // Call parent logic to apply the string filter on the title field
        return parent::applyFilter($query);
    }
}

Technisches Erstgespräch

Aus einem Package wird noch kein belastbares Produkt.

Wenn Architektur, Integration oder langfristiger Betrieb entscheidend sind, sprechen wir gern über den vollständigen Anwendungskontext.

Projekt besprechen