Skip to content
Advertisement

Laravel get values that contains string in where clause

I’m trying to get in where clause the cities that contains certain string.

For example, if I search for ‘Alexandria’ I want the results to have also ‘Alexandria’ and ‘Alexandria, Romania’ results.

I tried the following code but this is not working:

if(!is_null($city)){
  $query-> where('rent', '>=', $min_price)
  ->where('rent','<=',$max_price)
  ->where('city', 'like', '%'.$city.'%');
}

I also tried the following way but it throws ‘ Column not found: 1054’.

if(!is_null($city)){
  $query-> where('rent', '>=', $min_price)
  ->where('rent','<=',$max_price)
  ->where(strpos('city', $city) === true);
}

Can you please help me with some ideas on how can I solve this?

Thank you!

Advertisement

Answer

first explode $city by space and then use orWhere with like

if(!is_null($city)){
  $query-> where('rent', '>=', $min_price)
  ->where('rent','<=',$max_price)
  ->Where(function ($q) use($city) {
          $words = explode(' ',$city);
          foreach ($words as $word){
          $q->orwhere('city', 'like',  '%' . $word .'%');
      }      
   });
}

i think there are better solutions but this is what i found for now.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement