How to use the leftJoin() method on tables in a Laravel query

Overview

Left joining on two tables in a query is done when you need data from two or more tables, such as the users and their orders. If these tables are joined, they can generate useful reports for the admin, like how many orders each user has made.

Joining also allows you to retrieve the result from multiple tables as if they are one. In this shot, we will learn how to use the leftJoin() method in Laravel.

The leftJoin() method

The leftJoin() method is part of a query builder that is used to carry out the left joining table operation in Laravel.

Syntax

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

Parameters

The leftJoin() method receives multiple parameters:

  1. The table to be joined.
  2. Other parameters that are constraints for the join.

Example

use Illuminate\Support\Facades\DB;

public function index(){
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();// joining the posts table , where user_id and posts_user_id are same
          
return $users;

}

In the example above, we perform the left join from a controller and also import the DB class.

Explanation

We first get our primary table, users, i.e., the table that relates to the other tables we want to join. Then, we chain the primary table to the leftJoin() method.

As mentioned above, the first parameter is the table we want to join to the users table; in this case, it is the posts table. 'users.id', '=', and 'posts.user_id' are for constraints, and they mean joining the posts table, where users.id and posts.user_id are the same. We also chain the get() method, which retrieves the query results for us. Finally, we return the retrieved query results.

Free Resources