Tucker-Eric / EloquentFilter

An Eloquent Way To Filter Laravel Models And Their Relationships
http://tucker-eric.github.io/EloquentFilter
MIT License
1.72k stars 120 forks source link

Feature Request: map relation filter functions #91

Closed lkreher closed 4 years ago

lkreher commented 5 years ago

When defining a filter on a relation it would be great to also define which filter function to use. Currently the filter function on the related model has to be the same as the filter attribute on the original model. For example: I have a user model with a name filter. I have an issue model that has an author and an assignee. Currently I would have to write

class UserFilter extends ModelFilter
{
    public function name(string $name)
    {
        foreach (explode(' ', $name) as $part) {
            $this->where(function ($query) use ($part) {
                $query->where('first_name', 'LIKE', '%' . $part . '%')
                    ->orWhere('last_name', 'LIKE', '%' . $part . '%');
            });
        }

        return $this;
    }

    public function authorName(string $name)
    {
        return $this->name($name);
    }

    public function assigneeName(string $name)
    {
        return $this->name($name);
    }
}
class IssueFilter extends ModelFilter
{
    public $relations = ['author' => ['author_name'], 'assignee' => ['assignee_name']];
}

It would be great If I could just do:

class IssueFilter extends ModelFilter
{
    public $relations = ['author' => ['author_name' => 'name'], 'assignee' => ['assignee_name' => 'name']];
}

So when I filter by author_name on the issue model, I filter by the name-attribute on the author relation.

Tucker-Eric commented 5 years ago

I like it! Looks like it would be easy to implement without breaking backwards comparability. I'm open to a pr on this.

Tucker-Eric commented 4 years ago

Added in 2.2.0