+1 (252) 631 8899 +91 98212 12676

Laravel WhereIn Query Example

February 15, 2023

Laravel

Sumeet Shroff
By Sumeet Shroff
Laravel WhereIn Query Example

Introduction

Laravel provides a robust Query Builder that simplifies database operations. The "whereIn" method is a part of the Query Builder that allows you to filter data based on an array of values. This method is useful when you need to select data based on a list of values instead of a single value.

Syntax

The syntax of the "whereIn" method is as follows:

rustCopy code->whereIn('column_name', ['value_1', 'value_2', ..., 'value_n'])

Here, the first parameter is the name of the column you want to filter, and the second parameter is an array of values.

Example

Let's consider an example where we want to select all the users whose role is either "admin" or "superadmin" from the "users" table. The corresponding SQL query would be:

sqlCopy codeSELECT * FROM users WHERE role IN ('admin', 'superadmin');

We can achieve the same result using the "whereIn" method in Laravel, as shown below:

phpCopy code$roles = ['admin', 'superadmin'];
$users = DB::table('users')
            ->whereIn('role', $roles)
            ->get();

Here, we first define an array of roles we want to filter. We then use the "whereIn" method to filter the users based on their role.

Conclusion

In conclusion, the "whereIn" method in Laravel Query Builder is a powerful tool that allows you to filter data based on an array of values. By using the "whereIn" method, you can efficiently select data from your database without writing complex SQL queries. I hope this article has helped you understand the usage of the "whereIn" method in Laravel.

Sumeet Shroff

Loading...

Get 20% off on your first order

Get Started Now