Friday, September 5, 2025
HomeLanguagesLaravel whereIn, whereNotIn With SubQuery Example

Laravel whereIn, whereNotIn With SubQuery Example

Laravel whereIn and whereNotIn with subquery example. In this tutorial, you will learn how to use whereIn and whereNotIn subquery in laravel.

Sometimes you want to get nested data from database tables and some time exclude some nested data from DB table. So you can use whereIn and WhereNotIn subquery for that.

Laravel WhereIn SubQuery

The following examples queries fetch data from user table, which is available in the user_role table using whereIn subquery.

See the following examples:

Example 1: WhereIn SubQuery Using Query Builder

DB::table('users')->whereIn('id', function($query) {
    $query->select('user_id')->from('role_user');
})->get();

Example 2: WhereIn SubQuery Using Model

User::whereIn('id', function($query) {
    $query->select('user_id')->from('role_user');
})->get();

When you dump the above given whereIn subQueries you will get the following SQL query:

SELECT * FROM `users` WHERE `id` IN (
    SELECT `user_id` FROM `role_user`
)

Laravel WhereNotIn SubQuery

The following examples queries fetch data from user table, which is not available in the user_role table by using whereNotIn subquery.

See the following examples:

Example 1: whereNotIn SubQuery Using Query Builder:

DB::table('users')->whereNotIn('id', function($query) {
    $query->select('user_id')->from('role_user');
})->get();

Example 2: WhereNotIn SubQuery Using Model

User::whereNotIn('id', function($query) {
    $query->select('user_id')->from('role_user');
})->get();

When you dump the above given whereIn subQueries you will get the following SQL query:

SELECT * FROM `users`  WHERE `id` NOT IN (
    SELECT `user_id` FROM `role_user`
)

Conclusion

In this laravel where in and where not in subquery example tutorial, you have learned how to implement subquery using laravel whereIn and wherenotin eloquent methods in laravel.

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11864 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS