Laravel whereIn Eloquent Query Example

Laravel Eloquent whereIn query Example; In this tutorial, we will show you how to use eloquent whereIn query in laravel app. The SQL whereIn query is used with array and can be described with the whereIn() method.

The whereIn method uses “loose” comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value.

whereIn Query Syntax

Here is the wherein query syntax, as you can see, it takes two parameters. One parameter is the column’s id, and the second is the array of id.

whereIn(CoulumnName, Array);

Laravel whereIn() Query Example

whereIn() is used to check whether column contains value from the array or list. Basically, it is used to match column against list of values.

SQL Query:

SELECT * FROM USERS where id in (1,2,3,4);

Laravel Eloquent Query:

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

WhereIn Query with Laravel Model

Now, we are going to understand how can we write wherein query in laravel eloquent with model and DB::tables.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
    public function index()
    {
        $users = User::whereIn('id', ['1', '3', '5']) ->get();
        dd($users);
    }
}

WhereIn Query with Laravel Query Builder

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->whereIn('id', ['1', '3', '5']) ->get();
        dd($users);
    }
}

I hope you enjoy with laravel whereIn query example.

1 thought on “Laravel whereIn Eloquent Query Example”

Leave a Comment