How To Use WhereExists Builder In Laravel With An Example

In Laravel, you use the sql where exists clause. In your Laravel project, you can use the sql where exists clause. It is extremely simple to use and comprehend. In the where condition, you can use the SELECT statement. You can learn how to use whereExists in your app by looking at the example below.

SQL Query

SELECT *
FROM `items`
WHERE EXISTS
    (SELECT `items_city`.`id`
     FROM `items_city`
     WHERE items_city.item_id = items.id)

Using Laravel Query Builder

DB::table('items')
    ->whereExists(function ($query) {
        $query->select("items_city.id")
              ->from('items_city')
              ->whereRaw('items_city.item_id = items.id');
    })
    ->get();

All the best nerd!

Leave a Reply