Laravel – whereIn and whereNotIn with subquery example using query builder
In this post we will give you information about Laravel – whereIn and whereNotIn with subquery example using query builder. Hear we will give you detail about Laravel – whereIn and whereNotIn with subquery example using query builderAnd how to use it also give you demo for it if it is necessary.
As you know laravel is very popular php framework in today. So every point will be require for database related and that important. In this post i would like to share with you how to use subquery with whereIn and whereNotIn clause from scratch.
We may sometimes require to use select query with where in or where not in clause. we can simply make query using MySQL. But we don’t know how to use it on laravel query builder. However, In this example we will learn how to convert mysql query into laravel query builder of wherein with subquery. This example is from scratch, so i will give you first mysql query and then we will convert it into laravel query builder.
In this example i have to tables as listed bellow:
1) users
2) invite_users
Where In Query
In first query, basically we require users that only in invite_users table. we can normally retrieve using bellow sql query:
SQL Query:
SELECT * FROM 'users'
WHERE 'id' IN (
SELECT 'user_id' FROM 'invite_users'
)
As bellow we can convert for laravel application.
Laravel Query:
$users = DB::table("users")->select('*')
->whereIn('id',function($query){
$query->select('user_id')->from('invite_users');
})
->get();
Where Not In Query
In second query, basically we require users that not in invite_users table. we can normally retrieve using bellow sql query:
SQL Query:
SELECT * FROM 'users'
WHERE 'id' NOT IN (
SELECT 'user_id' FROM 'invite_users'
)
As bellow we can convert for laravel application.
Laravel Query:
$users = DB::table("users")->select('*')
->whereNOTIn('id',function($query){
$query->select('user_id')->from('invite_users');
})
->get();
I hope it can help you….
Hope this code and post will helped you for implement Laravel – whereIn and whereNotIn with subquery example using query builder. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs