diff --git a/README.md b/README.md index cb37a26..ac1b1cc 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,13 @@ Filters are done in the query parameters with the format `property:operator=term By default, if no operator is specified, it will default to `eq` so `name=Bob` will expand to `name:eq=Bob` +### Like & Not Like + +The string filter also supports like and not like operators. To use these you should use `*` as the wildcard +rather than `%` as you would in a typical database query. + +For instance `first_name:lk=Sam*` would match `Sam`, `Samuel` and `Samantha`. + ## Sorting You can set the fields that can be sortable when setting up your model. @@ -114,7 +121,7 @@ $sieve->setDefaultSort('name', 'asc') ### String -The basic filter. Ideal for textual data, implements `eq`, `neq`, `in`, and `nin` +The basic filter. Ideal for textual data, implements `eq`, `neq`, `in`, `nin`, `lk` and `nlk` ```php boolean() // defaults to 1 and 0 +$filter->boolean('Yes', 'No') // search for Yes and No in the database ``` ### Date diff --git a/src/Filters/StringFilter.php b/src/Filters/StringFilter.php index 31c34b2..19b5864 100644 --- a/src/Filters/StringFilter.php +++ b/src/Filters/StringFilter.php @@ -24,6 +24,9 @@ public function modifyQuery($query, SearchTerm $search) if ($search->operator() == 'lk') { $query->where($search->column(), 'LIKE', $this->prepareLike($search->term())); } + if ($search->operator() == 'nlk') { + $query->where($search->column(), 'NOT LIKE', $this->prepareLike($search->term())); + } } protected function prepareLike($term) @@ -67,6 +70,6 @@ private function shouldEscape($string, $pos) public function operators() { - return ['eq', 'neq', 'in', 'nin', 'lk']; + return ['eq', 'neq', 'in', 'nin', 'lk', 'nlk']; } } diff --git a/tests/Filters/StringFilterTest.php b/tests/Filters/StringFilterTest.php index 23df630..fee8a18 100644 --- a/tests/Filters/StringFilterTest.php +++ b/tests/Filters/StringFilterTest.php @@ -85,4 +85,17 @@ public function correctly_applies_lk_operator() $this->assertEquals('select * where "name" LIKE ?', $builder->toSql()); $this->assertEquals(['%t\est*'], $builder->getBindings()); } + + /** + * @test + */ + public function correctly_applies_nlk_operator() + { + $search = new SearchTerm('name', 'nlk', 'name', '*t\\\\est\\*'); + $builder = app(Builder::class); + + (new StringFilter)->modifyQuery($builder, $search); + $this->assertEquals('select * where "name" NOT LIKE ?', $builder->toSql()); + $this->assertEquals(['%t\est*'], $builder->getBindings()); + } } \ No newline at end of file