Laravel Eloquent whereIn Method Query Example

  531 views   6 months ago Laravel

Sometimes you might want to get records by array instead of specific value. Laravel whereIn() method uses SQL WHERE IN statement.

In this tutorial article, we are going to see Laravel whereIn eloquent query example. This will compare field with array instead of value. Laravel whereIn() method works well with Eloquent as well as query builder. Let's see both example for whereIn() method. Laravel whereIn method works well in get(), update() or delete() method.

WhereIn() method in Laravel Eloquent

In this example, we will use User model to get specific users with array if ids.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $users = User::whereIn('id', [1, 3, 5])
        ->get();
    
    dd($users);
}

WhereIn() method in query builder

In this example, we will use Illuminate\Support\Facades\DB facade to return specific users with array of ids.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $users = \DB::table('users')
        ->whereIn('id', [1, 3, 5])
        ->get();
    
    dd($users);
}

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]