So I have a collection of products ($this->products
) which I'm getting as a result of a Model query and I want to filter it by some of its attributes values. The problem is that Laravel doesn't have a method like orWhere
for collections like Eloquent does for querying models. Also I want to use the LIKE %{$searching_for}%
wildcard and I'm not sure how to use it (if possible at all) to filter my collection.
This is the code I tried to filter my collection with which obviously throws an Exception
that orWhere
method doesn't exist:
$products = $this->products
->where("field1", "LIKE %{$searching_for}%")
->orWhere("field2", "LIKE", "%{$searching_for}%")
->orWhere("field3", "LIKE", "%{$searching_for}%")
->orWhere("field4", "LIKE", "%{$searching_for}%");
I'd like to query the Model directly but I just store the $products
collection in Session so I can use it anywhere I need, I don't want to query the database too often so I'm searching for a solution to somehow filter the existing collection.
Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.
The merge methods merges the given $items with the items in the collection. The merge method will replace any item in the original collection's items if a string key with the same value exists in the supplied $items . If the $items keys are numeric, the new $items will be added to the end of the new collection's items.
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.
Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();
Similar to how Saravanan suggests doing it try this:
$products = $this->products->filter(function($product) use ($searching_for) {
return strstr($product->field1, $searching_for) ||
strstr($product->field2, $searching_for) ||
strstr($product->field3, $searching_for) ||
strstr($product->field4, $searching_for);
})
It is making sure to assign the filtered collection to a variable. It is also using strstr
as an alternative to stripos
though i doubt that is the cause of the issue.
Try using laravel collection's filter method.
collect($this->products)->filter(function($value) use ($search) {
return (stripos($value->field1, $search) ||
stripos($value->field2, $search) ||
stripos($value->field3, $search) ||
stripos($value->field4, $search));
});
Here $search is the value that you wanted to search.
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