Laravel whereExists and whereNotExists Query Example

Laravel whereExists and whereNotExists query; Through this tutorial, i am going to show you how to use whereExists and whereNotExists query in laravel apps.

Let, you have any job portal type application in laravel apps and the following tables into your job portal application; is as follows:

positions table

id | title | timestamps

users table

id | name | email | timestamps

users_position table (a pivot table for user and position)

id | user_id | position_id | description | timestamps

jobs table

id | position_id | name | description | timestamps

Laravel whereExists and whereNotExists Query Example

  • Laravel whereExists Using Eloquent Model
  • Laravel whereNotExists Using Eloquent Model

Laravel whereExists Using Eloquent Model

For example; if you have a lot of users registered in job portal app. And want to send email to users who are Banker; is as follows:

$users = User::whereExists(
               function($query) use($job) {  
                 $query->from('users_position')
                       ->where('position_id', $job->position_id);
               })->get();        
return $users;

Laravel whereNotExists Using Eloquent Model

For example; if you have a lot of users registered in job portal app. And do not want to send email to users who are Banker; is as follows:

$users = User::whereNotExists(
               function($query) use($job) {  
                 $query->from('users_position')
                       ->where('position_id', $job->position_id);
               })->get();        
return $users;

Recommended Laravel Tutorials

Leave a Comment