Cepheus
Cepheus

Reputation: 4913

How to perform conditional queries

I have a table with 3 columns. I'd like to perform queries based on whether the corresponding checkbox is checked. I'm not getting any results where I actually expect matching results. How can I achieve this?

Here's what I've tried with no success:

$products = OtherProduct::orderBy('id', 'DESC');
if($request->col1) {
  $products->where('col1', 'value to search');
}
if($request->col2) {
  $products->where('col2', 'value to search');
}
if($request->col3) {
  $products->where('col3', 'value to search');
}
$products->get();

Upvotes: 0

Views: 54

Answers (2)

DevK
DevK

Reputation: 9962

Use ->when(..) for conditionals:

$products = OtherProduct::orderBy('id', 'DESC')
    ->when($request->col1, function ($query) {
        return $query->where('col1', 'value to search');
    })
    ->when($request->col2, function ($query) {
        return $query->where('col2', 'value to search');
    })
    // ..
    ->get();

Upvotes: 4

Sagar Gautam
Sagar Gautam

Reputation: 9389

Use Laravel newQuery() and then your code should look like

$products = OtherProduct::newQuery();

// Search for a product based on col3
if ($request->has('col1')) {
    $products->where('col1', $request->input('col1'));
}

// Search for a product based on col2
if ($request->has('col2')) {
    $products->where('col2', $request->input('col2'));
}

// Search for a product based on col3
if ($request->has('col3')) {
    $products->where('col3', $request->input('col3'));
}

// Continue for all of the filters.

// Get the results and return them.
return $products->orderBy('id', 'DESC');->get();

Upvotes: 0

Related Questions