0

I have this query:

if($keyword){
    array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}

The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).

I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.

For the example:

if($fromPrice){
    array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
    array_push($where, ['price', '<=', $toPrice]);
}

And the query is:

$cars= Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where)->paginate(10);

I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.

Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

2 Answers 2

1

to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:

$query = Property::with(array(
    'photos'=>function($query){
            $query->select(['car_id', 'name']);
        }
))->where($where);

if($keyword){

     $query = $query->where(function ($query) use ($keyword) {
                  $query->where('name_fr', 'like', $keyword)
                  ->orWhere('name_en', 'like', $keyword);
     });
}

$cars = $query->paginate(10);
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I have another sets of where. I have $where ['id' =>, ''... ] AND (if keyword exists) WHERE keyword LIKE this column or keyword like another column. But I see I can't use ->where($where)->where( // keyword query)
If I remove the first query Property::with, the query by keyword works fine. With it doesn't. Without keyword first query works, of course.
Ok, I have made it with three parts. First check if(count($where)), then apply it, 2. check keyword and latest execute and it works fine. Thanks :).
1

You can also go with

$propertyQuery = Property::query();
if($keyword){
   $propertyQuery->where(function($query) use ($keyword){
                    $query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
           });
         }
$cars = $propertyQuery->paginate(10);

1 Comment

The problem is that I have another sets of where. I have $where ['id' =>, ''... ] AND (if keyword exists) WHERE keyword LIKE this column or keyword like another column.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.