Laravel 8 Left Join Query Example

In this article, we will see laravel 8 left join query example. laravel left join eloquent returns all rows from the left table, even if there are no matches in the right table. The result is NULL from the right side. 

We will also see a query of laravel left join with groupBy(). If you would like to perform a "left join" or "right join" instead of an "inner join", use the leftJoin or rightJoin methods. These methods have the same signature as the join method.

For laravel left join query example we need the first argument passed to the leftJoin method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Left join query use in laravel 6, laravel 7, laravel 8.

So, let's see an example of left join in laravel 8 or laravel 8 join two tables.

laravel 8 Left Join


SQL Query:

In this example, we will create users table and a countries table. We will add the country_id  foreign key to the user's table. So, when I get users at that time we will get the country name from country_id using an inner join.

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;



select `users`.`id`, `users`.`name`, `users`.`email`, `countries`.`name` as `country_name` 
from `users` 
left join `countries` on `countries`.`id` = `users`.`country_id`


Laravel Query:

In this example, select data like id, name email, and country name but if you want all fields then you can use * to select all data.

public function index()
    $users = User::select('', '', '', ' as country_name')
                    ->leftJoin('countries', '', '=', 'users.country_id')

 Using DB:

$users = DB::table('users')
            ->leftJoin('posts', '', '=', 'posts.user_id')



Laravel Left Join with Multiple Condition

Now, We will give you an example of multiple where condition with an aggregate function.

User::leftJoin('posts', '', '=', 'posts.user_id')
       ->where('is_published', true)


You might also like:


Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.