Skip to content
Advertisement

Laravel query find comma separated and normal string

I got a column called fac that values can be a single number like 2 and also can be comma separated like 2,4,5

enter image description here

I want to get data from database via api. Also value can be a single or comma separated too. so user can search like these:

localhost/api/search {fac: 1}

Or

localhost/api/search {fac: 1,4,5}

I used find_in_set but look like it not working in this case:

$fac = request('fac');

->whereRaw("find_in_set({$fac}, fac)")->get();

If I run this localhost/api/search {fac: 1} it return nothing, if I run localhost/api/search {fac: 1,4,5} it give me error:

Syntax error or access violation: 1582 Incorrect parameter count in the call to native function ‘find_in_set’

Goal:

If user search 1 it should return all data that contains 1, if search 1,7 should return all data that contains 1 and 7

Advertisement

Answer

First, convert your comma-separated string to an array. And create raw query.

$fac = request('fac'); // single value or comma saperated string
$data = explode(',',$fac);
$str='';
$i=1; // to append AND in query

foreach ($data as $key => $value) {
  $str .= 'FIND_IN_SET("'.$value.'" ,fac)';
  if($i < count($data)){
    $str .=' AND '; // use OR as per use
  }
  $i++;
}

Now $str will contain raw query

FIND_IN_SET("1", fac) AND FIND_IN_SET("7", fac)

and you can use in eloquent.

->whereRaw($str)->get();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement