Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection Where LIKE Laravel 5.4

Tags:

laravel

I know collection doesn't support where LIKE but how can I achieve this.

My data is: enter image description here

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

Laravel doesn't support where like in the collection. I'm thinking to use

collect($products)->filter( function () use ($productName) {    
    return preg_match(pattern, subject);
});

But I don't know how to do it. TY

like image 671
Rbex Avatar asked May 22 '17 02:05

Rbex


People also ask

What is collection Laravel 8?

Laravel collections can be regarded as modified versions of PHP arrays. They are located in the Illuminate\Support\Collection directory and provide a wrapper to work with data arrays. In the code snippet above, we used the collect() method to create a Collection instance from the defined array.

How do I combine two collections in Laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.

What is eloquent collection?

The Eloquent collection object extends Laravel's base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!


1 Answers

On a collection you can use the filter($callback_function) method to select items in the collection. Pass in a callback function that returns true for every item that should be returned.

In your case you can use the stristr() function to emulate a LIKE operator, like this:

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 what ever you need to match strings.

This will return the collection in its original structure minus the non matching items.

like image 104
aljo f Avatar answered Oct 09 '22 15:10

aljo f