How To Use WhereIn Query in Laravel

In this blog, I will be going to explain to you how you can match a column with an array of values from your database table column. This will be going to be very easy and it helps in complex query structure as well. 


Syntax for WhereIn 

whereIn(Coulumn_name, Array);


Now, we are going to understand with the help of SQL Query:


SELECT *

  FROM users

  WHERE id IN (4, 5, 6) 


Let's implement the SQL Query in Laravel Query Model:


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use App\User;

class UserController extends Controller

{

    public function index()

    {

        $users = User::select("*")

                        ->whereIn('id', [4, 5, 6])

                        ->get();      

        dd($users);                    

    }

}


Another method using  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);

    }

}



Here is another example of wherein query. You can work with a comma-separated string value. you can work as like bellow:


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use App\User;

class UserController extends Controller

{

    public function index()

    {

        $myString = '1,2,3';

        $myArray = explode(',', $myString);


        $users = User::select("*")

                    ->whereIn('id', $myArray)

                    ->get();

    }

}



I hope this will help you with your code. Let me know in the comments if you have any doubts.