Laravel Eloquent LEFT JOIN WHERE NULL
In Laravel, you can use the leftJoin
method on a query builder instance to perform a left join, and then use the whereNull
method to only include records where a column from the right-hand table is null:
<?php
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->whereNull('posts.id')
->get();
This will select all users, and any matching posts. If a user does not have any posts, the columns from the posts
table will be null
. The whereNull
condition will only include users for which the id
column from the posts
table is null
, meaning they do not have any posts.
The resulting collection will contain all columns from the users
table, and any columns from the posts
table that match the leftJoin
condition, with null
values for the columns from the posts
table for users that do not have any posts.