0

How can I implement this in Eloquent?.

select * from product where name like '%value%' and (product_type = product_type_param or product_type_param = 0);

If a product_type_param value of 0 is supplied, it will select products of all types, taking into account that the name also matched, of course.

My current code:

$result = Product::where( [  ['name', 'like', '%' . 
$searchAttributes['name'] . '%'],
    ['product_type', '=', $searchAttributes['product_type']]]
     )->get();

The idea would be something like this (excuse the example, it only shows my intention):

 ['product_type', '=', $searchAttributes['product_type']] or [$searchAttributes['product_type'] == 0]]

Should I execute a raw query?

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
notExactlyAHero
  • 353
  • 1
  • 4
  • 14

2 Answers2

1

You can use a closure function to scope the query

Product::where('name', 'like', '%' . $searchAttributes['name'] . '%')
        ->where(function($q) use ($searchAttributes) {
             $q->where('product_type', $searchAttributes['product_type'])
               ->orWhere('product_type_param', 0);
        })->get();
Chay22
  • 2,834
  • 2
  • 17
  • 25
0

using orWhere:

  Product::where([
       ['column','value'],
       ['another_column','value'],
   ])->orWhere([
      ['column','value']
   ])->get();
Hussein
  • 1,143
  • 1
  • 9
  • 16