0

I have an array, say $array, that I'd like to pass into a query executed using the Laravel DB:select method, eg.:

$results=DB::select("select * from table where id in ?",[$array])

How can I do this? Passing in like the above gives me an Array to string conversion error.

This is MariaDB

I have seen this Laravel 4: DB::select with IN statment, which is not sufficient for my needs ("Use a proper query").

Program.X
  • 7,250
  • 12
  • 49
  • 83

1 Answers1

1

Use the full query builder instead of just a select query:

$results = DB::table('table_name')
       ->whereIn('id',[1,2,3,4])
       ->get();
aynber
  • 22,380
  • 8
  • 50
  • 63
  • Sorry, this is not appropriate to my needs. The query is very complex and I require testability and control over the SQL. I do need to use DB::select. – Program.X Aug 30 '23 at 16:19
  • @Program.X Laravel tests the framework extensively, including things like the `whereIn` calls. You can use `whereRaw()` and `selectRaw()`, if you must, or `DB::statement()` to go super low-level. – ceejayoz Aug 30 '23 at 16:20
  • If it's a complex query, then show the complex query. You showed a simple query, so I provided the solution for a simple query. Laravel allows for much more complex queries, even with raw statements – aynber Aug 30 '23 at 16:43
  • Thank you for your help. It looks like my requirement is not possible. As mentioned, it is not appropriate to use the query builder in Laravel. (SQL is platform agnostic in this context, regardless of complexity). – Program.X Aug 31 '23 at 10:53
  • You can with the linked dupe. It just means you need to build out the number of question marks with parenthesis, instead of a single question mark – aynber Aug 31 '23 at 11:44