Are you struggling to manage hefty datasets in your Laravel app?
Discover the WHEREIN query. Laravel now offers the whereIn() method, allowing comparison of multiple values with columns. This function cross-references a list of data with a column, returning results if the column contains any of those specified values. This robust feature in Laravel’s Eloquent ORM streamlines data filtering, making it effortless to sift through based on your specified values.
What does the Laravel Eloquent WHEREIN Query do?
With the Laravel Eloquent whereIn method, you can refine your database queries by specifying a list of values from a single column. Essentially, it functions similarly to the SQL IN operator. This feature proves useful for fetching records that meet particular conditions within a predefined set of choices.
Let’s learn more:
Sometimes we have a bunch of data or an array, and we want to compare it with columns in a single SQL query
So in that case the SQL IN() function is often used
Ex. Select * from users where id IN (1,2,3);
To execute this query Laravel provide whereIn / whereNotIn functions
Ex.
$ids = [1,2,3,4,5];
$users = User::whereIn(`id`,$ids)->get(); // Using model
Or
$users = DB::table(‘users’)->whereIn(`id`,$ids)->get(); // using db table
Ex. $users = User::whereIn(`id`,$ids)->OrWhereNotIn(‘status’, [‘ACCEPTED’,’SELECTED’,’REJECTED’]);
// list of employees who have been accepted or selected, or are based in Denvar or Chicago, and, they should have in any of the specified skills.
$employee = Employe::
->whereIn(‘status’, [‘accepted’, ‘selected’])
->whereIn(‘city’, [‘Denvar’, ‘Chicago’], ’or’,false)
->whereIn(‘skill’, [‘php’, ‘.net’, ‘jquery’])
Need help building or optimizing your Laravel applications? Stay tuned with me for more interesting question and answer related to Laravel, Python, ReactJS and more.