1

How would I do a conditional laravel query taking in consideration what I try and did not work, where I try to get get products with a specifc name if name is not empty

This one is not working!!

public function getProducts($page = null, $match=null, $price = null) {
    if ($page != null)
        DB::getPaginator()->setCurrentPage($page);
        $products = Product::join('product_specs', 'products.productid', '=', 'product_specs.product_id')
                ->join('feeds_categories', 'product_specs.category', '=', 'feeds_categories.id')
                ->where('feeds_categories.name', '=', 'Notebooks')
                ->where('products.status', '=', 1)
                ->where('products.price', '>', 250)
                ->orderBy('products.price', 'ASC')
                ->paginate(10);
   if($match !='') $products->where('productname','LIKE','%'.$match.'%');    
   return $products;
}
1
  • An empty string and null are different. Have you tried testing $match for null? Commented Jul 4, 2014 at 21:17

1 Answer 1

2

You did not reassign the query builder back to the $products variable. Try this:

if($match !='') $products = $products->where('productname','LIKE','%'.$match.'%');

In fact, you will also need to move it before ->paginate(10) as well.

public function getProducts($page = null, $match=null, $price = null) {

        ...
        ->where('products.price', '>', 250); // Notice I added a semi-colon here.

    if($match !='') $products = $products->where('productname','LIKE','%'.$match.'%'); 

    $products = $products->orderBy('products.price', 'ASC')
        ->paginate(10);

    return $products;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.