I'm trying to bind an array in a raw WHERE IN
query in the Laravel DB
example:
$arr = [1,2,3];
DB::select(DB::raw("select * from test1 WHERE id IN ? "), [$arr]);
for some reason the array is not being changed to the following query:
select * from test1 WHERE id IN (1,2,3)
does someone know if I can do this somehow?
try it in laravel:
$arr = [1,2,3];
$result = DB::table('test1')->whereIn('id', $arr)->get();
dd($result);
And use this one for your raw query:
$arr = [1,2,3];
$arr = join(",",$arr);
$result = DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (".$arr.")"));
dd($result);
For preventing sql injection you use something like which i have mentioned below.
$arr = [1,2];
$arr = join(",",$arr);
$result = DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (?,?)"),$arr);
dd($result);
it will be work for you.
or
DB::table("test1")->whereIn('id', $arr)->get();
https://laravel.com/docs/5.4/queries#where-clauses
or Eloquent :
$q= TestModel::where('id',$arr)->get();