@@ -226,6 +226,53 @@ public function search(string $query): self
226
226
return $ this ;
227
227
}
228
228
229
+ /**
230
+ * Add a fuzzy search to the query.
231
+ *
232
+ * @param mixed $key
233
+ * @param string $query
234
+ * @param bool $caseSensitive
235
+ * @param string $boolean
236
+ *
237
+ * @return self
238
+ * @throws ReflectionException
239
+ */
240
+ public function fuzzySearch (
241
+ mixed $ key ,
242
+ string $ query ,
243
+ bool $ caseSensitive = false ,
244
+ string $ boolean = '& ' ,
245
+ ): self {
246
+ $ tokenizedQuery = explode (' ' , $ query );
247
+ $ keys = collect ($ key )->crossJoin ($ tokenizedQuery )->toArray ();
248
+
249
+ return $ this ->whereNested (function ($ query ) use ($ keys , $ caseSensitive ) {
250
+ foreach ($ keys as $ v ) {
251
+ $ query ->whereLike ($ v [0 ], $ v [1 ], $ caseSensitive , '| ' );
252
+ }
253
+ }, $ boolean );
254
+ }
255
+
256
+ /**
257
+ * Add an "or fuzzy search" to the query.
258
+ *
259
+ * @param mixed $key
260
+ * @param string $query
261
+ * @param bool $caseSensitive
262
+ * @param string $boolean
263
+ *
264
+ * @return self
265
+ * @throws ReflectionException
266
+ */
267
+ public function orFuzzySearch (
268
+ mixed $ key ,
269
+ string $ query ,
270
+ bool $ caseSensitive = false ,
271
+ string $ boolean = '| ' ,
272
+ ): self {
273
+ return $ this ->fuzzySearch ($ key , $ query , $ caseSensitive , $ boolean );
274
+ }
275
+
229
276
/**
230
277
* Add a basic where clause to the query.
231
278
*
@@ -431,8 +478,8 @@ private function generateWhereLikeClause($key, $value, $caseSensitive, $operator
431
478
}
432
479
433
480
$ operator = $ caseSensitive ? $ operator : $ insensitiveOperator ;
434
- $ prefix = $ hasPrefix ? '* ' : '' ;
435
- $ suffix = $ hasSuffix ? '* ' : '' ;
481
+ $ prefix = $ hasPrefix || ! $ hasSuffix ? '* ' : '' ;
482
+ $ suffix = $ hasSuffix || ! $ hasPrefix ? '* ' : '' ;
436
483
$ value = json_encode ($ value , JSON_THROW_ON_ERROR );
437
484
$ value = Str::start (Str::finish ($ value , $ suffix ), $ prefix );
438
485
0 commit comments