laravel-json-api / eloquent

Serialize Eloquent models to JSON API resources
MIT License
12 stars 15 forks source link

[Feature] Create WhereSearch filter to search multiple columns #26

Open llebc opened 2 years ago

llebc commented 2 years ago

I don't know how much use this will be if at all but I find myself duplicating a bit of logic in order to perform across multiple columns within a dataset.

This filter just applies a LIKE to all of the columns which have been in, meaning a query can be made to search across multiple fields hence the WhereSearch.

In order to user this filter it just needs to be added to the schema like other filters.

public function filters(): array
{
    return [
        WhereSearch::make('search', 'name|email')
    ];
}

In order to use query parameters to search the URL would be https://localhost/users?filter[search]=SearchingMultipleColumns.

This produces a query like the following:

select * from `users` where `name` LIKE ? or `email` LIKE ?

The multiple columns are searched across by separating the columns with a pipe.

llebc commented 2 years ago

Not sure if this would of any use but as I use it a fair amount I wanted to contribute to the open source project 😃 .

llebc commented 2 years ago

@lindyhopchris

Many thanks for the feedback. Much appreciated, to be honest, because I've used it for one purpose in my projects I didn't really think about making it dynamic, the name WhereSearch is actually WhereContains in my personal project however, I agree the convention WhereLike is much better and it's obvious what it's doing.

The only thing I changed from your feedback was change it from "beginsWith" to "startsWith" as I believe this is the convention for most methods such as the helper Str::startsWith so I thought keeping it the same convention as that!

haddowg commented 2 months ago

This would be supported with WhereAny from https://github.com/laravel-json-api/eloquent/pull/38 and ->using('like') in fact my test case is exactly this