mardi 14 février 2017

Laravel 5: Alternative for Eloquent's 'orWhere' method for querying collections

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire