Laravel whereIn, whereNotIn eloquent query example

Laravel whereIn, whereNotIn eloquent query example

In this article lets understand Laravel whereIn, whereNotIn eloquent query with example. We will also look at the  orWhereIn , orWhereNotIn here.

1.  whereIn query

Laravel syntax :

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

Plain syntax: Select * from users where id in (1,2,3,4);

Basically it is very easy from syntax to understand but whereIn method verifies that a given column’s value is contained within the given array. The above query will check users that have ids from passed array.

Result :

whereIn

2.  whereNotIn query

Laravel syntax :

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

Plain syntax: Select * from users where id not in (1,2,3,4);

whereNotIn does the reverse of what we did in first query. It will exclude the results of passed array and returns the rest of records.

Result :

whereNotIn

3.  orWhereIn query

Laravel syntax :

$users = User::where('type','=','customer')
        ->orWhereIn('id', [1, 2, 3])->get();

Plain syntax: select * from `users` where `type` = ‘customer’ or `id` in (1,2,3);

Where you want to apply condition on multiple column and check if one of the column has one of the values from array orWhereIn can be used. In above example we are looking for records on user table with type customer or if ids from passed values.

Result :

orWhereIn

4.  orWhereNotIn query

Laravel syntax :

$users = $users = User::where('type','=','customer')
        ->orWhereNotIn('id', [1, 2, 3])->get();

Plain syntax: select * from `users` where `type` = ‘customer’ or `id` not in (1,2,3);

See result below where id 2 is not in array but it has type customer so will be

Result :

orWhereNotIn

That’s all on Laravel whereIn, whereNotIn eloquent query example. Also orWhereIn ,orWhereNotIn. Hope this finds you helpful.

See other articles on Laravel here.