How to Make Laravel Eloquent "IN" Query?

PhpLaravelOrmEloquent

Php Problem Overview


I want to make query in Laravel Eloquent like here its raw MySQL query

SELECT  * from  exampleTbl where id in(1,2,3,4)

I have tried this in Laravel Eloquent but it's not working

DB::where("id IN(23,25)")->get()

Php Solutions


Solution 1 - Php

Here is how you do in Eloquent

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

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

Solution 2 - Php

If you are using Query builder then you may use a blow

DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()

If you are working with Eloquent then you can use as below

$sendUsersList = Newsletter Subscription:: select ('*')
                ->whereIn('id', $send_users_list)
                ->get();

Solution 3 - Php

Syntax:

$data = Model::whereIn('field_name', [1, 2, 3])->get();

Use for Users Model

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

Solution 4 - Php

As @Raheel Answered it will be fine but if you are working with Laravel 6/7

Then use Eloquent whereIn Query.

Example1:

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

Example2:

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

Example3:

$ids = [1,2,3];

$users = User::wherein('id',$ids)->get();

Solution 5 - Php

Since Laravel 5.7, there is a method whereIntegerInRaw. The execution time is faster than whereIn.

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

User::whereIntegerInRaw('id', [1, 2, 3])->get();

You can see the PR.

Solution 6 - Php

Maybe you wanna use whereRaw($query)

Your Code :

DB::where("id IN(23,25)")->get()

Into :

DB::whereRaw("id IN(23,25)")->get()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavi JethvaView Question on Stackoverflow
Solution 1 - PhpRaheelView Answer on Stackoverflow
Solution 2 - PhpNikunj K.View Answer on Stackoverflow
Solution 3 - PhpMd. Saidur Rahman MilonView Answer on Stackoverflow
Solution 4 - PhpGufran HasanView Answer on Stackoverflow
Solution 5 - PhpSachin KirantiView Answer on Stackoverflow
Solution 6 - PhpNsgtView Answer on Stackoverflow