Efficient data filtering with whereIn() in Laravel

Efficient data filtering with whereIn() in Laravel

Published
Nov 17, 2023
Written by
Benjamin Crozat
0
comments
2 minutes
read

Introduction to Laravel’s whereIn() method in the query builder

When you’re diving into Laravel’s query builder, one of the handy tools in your arsenal is the whereIn() method.

It’s a straightforward yet powerful way to filter your database queries.

Think of it like a tool helping you pick exactly what you need from a list of items in your database.

How whereIn() works

Imagine you have a list of user IDs, and you need to fetch users that match these IDs from your database.

That’s where Laravel’s query builder whereIn() method comes into play.

It allows you to specify a column, like user_id, and a set of values. The framework then fetches rows where the column’s value is in the provided set.

Using whereIn() in your code

Here’s a quick example:

$users = User::whereIn('id', [1, 2, 3])->get();

In this snippet, the whereIn() method is fetching users whose id is either 1, 2, or 3.

Without whereIn(), you whould have to do something like this:

$users = User::where('id', 1)
	->orWhere('id', 2)
	->orWhere('id', 3)
	->get();

When not to use whereIn()

While whereIn() is handy, it’s important to use it wisely.

If you have a massive array of items you’re filtering by, this can slow down your query. So, always try to limit the size of the array you pass to whereIn().

Instead, I would try to find the common denominator between all those items and use that to run my queries faster.

About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub