0

I am trying to use an array in the WHERE clause with IN () in Laravel, but it's not working as expected. Here’s my current code:

$groupOfTopics = [46, 51, 167, 176, 177, 181, 185, 270, 323, 328, 350];
$Data = DB:: connection('DB')->select(
"Select
....
WHERE code IN (?)", [$groupOfTopics],);

However, this does not return the expected results.

How can I correctly pass an array into the IN clause in Laravel raw queries?

6
  • 1
    Why not use DB::connection('DB')->select(/* ... */)->whereIn('code', $groupOfTopics)? Commented Mar 11 at 17:51
  • This project requires standardization, and in the rest of it the code is in raw queries. So I rather use it as well, to not be the guy that don't follow the standard Commented Mar 12 at 11:14
  • 1
    Having standards and being consistent is all well and good, but you're not using Laravel to it's full potential if you always use the DB facade... Do you also not use Models and Relationships? I'd be very interested to hear why this choice was made; I can't really think of any good reasons you'd use DB::connection('db')->select(/* entire raw query */) over Model::select(...)->where(...)->get() (and similar). Commented Mar 12 at 12:46
  • 1
    Haha ok, totally understandable. Again, not trying to get you to change your approach or anything, was simply very curious why that decision was made. "Because my senior(s) said so" is (unfortunately) a pretty common answer 😅 Cheers! Commented Mar 12 at 19:11
  • 1
    I am very thankful nonetheless. So... Thanks!!! Commented Jun 12 at 14:23

1 Answer 1

0

To use an array in the WHERE clause, IN (), you need to create as many "?" as there are items in the array. A simple foreach or for loop before the SELECT clause will do. In the loop, for each item in the array, you will add "?" to a string $numberOfItems. So, if there are 4 items in the array, the string will look like this: ?, ?, ?, ?

In place of WHERE code IN (?), it will be WHERE code IN ($numberOfItems), which is equivalent to WHERE code IN (?, ?, ?, ?).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.