Efficient data filtering with whereIn() in Laravel

Efficient data filtering with whereIn() in Laravel

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:

$userIds = [1, 2, 3];

Step 2: Use whereIn() in Eloquent

$users = \App\Models\User::whereIn('id', $userIds)->get();

This will generate the SQL:

SELECT * FROM users WHERE id IN (1, 2, 3);

Step 3: Use whereIn() in Query Builder

$users = DB::table('users')->whereIn('id', $userIds)->get();

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:

$users = \App\Models\User::whereIn('id', [1, 2, 3]) ->where('status', 'active') ->get();

Step 5: Use whereIn() with Relationships

Example: Get posts by authors whose IDs are in a list.

$authorIds = [5, 6, 7]; $posts = \App\Models\Post::whereIn('user_id', $authorIds)->get();

Tips

  • Use whereNotIn() to exclude values:

User::whereNotIn('id', [1, 2, 3])->get();
  • You can pass any array—dynamic or hardcoded.

Real-World Example in Controller

public function filterUsers(Request $request) { $ids = $request->input('ids'); // e.g., [2, 5, 9] $users = User::whereIn('id', $ids)->get(); return view('users.index', compact('users')); }

Testing in Tinker

Use Laravel Tinker to test:

php artisan tinker
App\Models\User::whereIn('id', [1, 2])->get();
Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close