Laravel whereIn, whereNotIn With SubQuery Example - Yudhy Network

Share on:

Yudhy Network - Laravel where In and where Not In subquery example. In this tutorial, you will learn how to use laravel whereIn() & whereNotIn() method to buiding subquery

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

Recommended:- Laravel Multiple Where Conditions Example
Recommended:- Laravel Eloquent whereRaw Query Example
Recommended:- Laravel – where In Eloquent Query Example
Recommended:- Laravel whereIn, where Not In With SubQuery Example
Recommended:- Laravel where Like Query Example
Recommended:- Laravel where Between Dates Eloquent Query
Recommended:- Laravel where Not In Eloquent Query Example
Recommended:- Laravel WhereHas Eloquent Example
Recommended:- Laravel where Not Between Query Example
Recommended:- Laravel whereExists and where Not Exists Query Example
Recommended:- Laravel Pluck Method Example
Recommended:- Laravel Where Null and Where Not Null Query
Recommended:- Laravel Group by Example
Recommended:- Laravel Order by Example
Recommended:- Laravel InsertOrIgnore Example

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus