Collection where LIKE Laravel 5.4

I know that the collection does not support where LIKE is, but how can I achieve this.

My details: enter image description here

collect($products)->where('name', 'LIKE', '%'. $productName . '%');

Laravel does not support, as in the collection. I think to use

collect($products)->filter( function () use ($productName) {

            return preg_match(pattern, subject);
        })

but I don’t know how to do it. Ty

+4
source share
2 answers

You can do it:

collect($products)->filter(function ($item) use ($productName) {
    // replace stristr with your choice of matching function
    return false !== stristr($item->name, $productName))
)

Just replace stristr with preg_match or whatever you like.

This will return the collection to its original structure minus the non-matching elements.

+5
source

Another option is to add a sentence WHERE LIKEwhen you query the database (first collect the collection) instead of getting all the elements and then filtering.

For instance:

$products = Product::where('name', 'like', '%match%')->get();

SQL ( ), .

0

Source: https://habr.com/ru/post/1677657/


All Articles