laravel-model-filter

This is the documentation for v4. You can switch versions in the menu at the top. Check your current version with the following command:

composer show lacodix/laravel-model-filter

Filter for Relations

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);
    }
}