Courtney White
Courtney White

Reputation: 614

Eloquent Conditional orWhere

I've got a search box that searches over products. The way I want it to work is if I search for a product name and it exists then it returns the products that match the search. If the search doesn't match the name of any products I want it to then search through the product descriptions instead. Here is what I've tried

$products = Product::where(function ($query) use ($terms) {
            foreach ($terms as $term) {
                // Loop over the search terms
                $query->orWhere('name', 'like', '%' . $term . '%');
            }
        })->latest()->paginate($productsPerPage);

        if(empty($products)){
            $products = Product::where(function ($query) use ($terms) {
              foreach ($terms as $term) {
                  $query->orWhere('description', 'like', '%' . $term . '%');
              }
          })->latest()->paginate($productsPerPage);
        }

However this does not work, if the search contains a product description it doesn't return any results.

Upvotes: 0

Views: 623

Answers (1)

MaartenDev
MaartenDev

Reputation: 5792

empty($products) doesn't work because the paginate call always returns an LengthAwarePaginator instance and thus isn't empty

the following code can be used:

   $products = Product::where(function ($query) use ($terms) {
        foreach ($terms as $term) {
            // Loop over the search terms
            $query->orWhere('name', 'like', '%' . $term . '%');
        }
    })->latest()->paginate($productsPerPage);

    if ($products->total() == 0) {
        $products = Product::where(function ($query) use ($terms) {
            foreach ($terms as $term) {
                $query->orWhere('description', 'like', '%' . $term . '%');
            }
        })->latest()->paginate($productsPerPage);
    }

Upvotes: 2

Related Questions