What is whereIn()
?
whereIn()
is a Laravel Eloquent/Query Builder method that adds a WHERE IN (...)
clause to your SQL query. It is used to filter records where a column's value exists within a given array.
Use Case Example
Let’s say you have a users
table and you want to get all users whose id
is either 1
, 2
, or 3
.
Step-by-Step Tutorial
Step 1: Define Your Data
Define the list of values you want to filter against:
Step 2: Use whereIn()
in Eloquent
This will generate the SQL:
Step 3: Use whereIn()
in Query Builder
It works the same way and is useful when you're not using Eloquent models.
Step 4: Add Additional Conditions (Optional)
You can chain whereIn()
With other conditions:
Step 5: Use whereIn()
with Relationships
Example: Get posts by authors whose IDs are in a list.
Tips
-
Use
whereNotIn()
to exclude values:
-
You can pass any array—dynamic or hardcoded.
Real-World Example in Controller
Testing in Tinker
Use Laravel Tinker to test: