I know collection doesn't support where LIKE but how can I achieve this.
My data is:
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
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With