Laravel框架与SQL WHERE IN语句冲突问题及解决方案咨询
Hey there! Your judgment is correct—this isn’t a "conflict" with Laravel, but a common mistake in how parameter bindings work for IN clauses. Let’s break down the issue and fix it.
Why Your Code Fails
The error prepareBindings() must be of the type array, string given occurs because:
- When using prepared statements with
IN, each value in the list needs its own placeholder (?), not a single placeholder for a comma-separated string. - Your code passes
implode(',',$terms)(a string) as the binding, but Laravel expects an array of values to map to each placeholder.
Solution 1: Fix the Raw Query
If you want to stick with raw SQL, generate multiple placeholders matching the number of terms, then pass the original $terms array as bindings:
// Split the search string into terms $terms = explode(" ", $term); // Generate placeholders (e.g., "?,?" for 2 terms) $placeholders = implode(',', array_fill(0, count($terms), '?')); // Execute the query with proper bindings $posts = DB::select("SELECT * FROM car WHERE model IN ($placeholders)", $terms);
Solution 2: Use Laravel's Query Builder (Recommended)
Laravel’s query builder handles WHERE IN clauses cleanly and safely, so you don’t have to mess with placeholders manually:
// Split the search string into terms $terms = explode(" ", $term); // Use query builder for readable, secure code $posts = DB::table('car') ->whereIn('model', $terms) ->get();
This method automatically escapes your values to prevent SQL injection and handles placeholder generation behind the scenes—much more idiomatic for Laravel!
Key Takeaway
Never pass a comma-separated string as a single binding for IN clauses. Always use an array of values paired with matching placeholders, or let Laravel’s query builder do the heavy lifting for you.
内容的提问来源于stack exchange,提问作者seamus

