Using ‘LEFT JOIN’ in Laravel Eloquent

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, the widely-celebrated PHP framework for web artisans, includes an elegant ORM (Object-Relational Mapper) named Eloquent. Among its features is the ability to construct efficient database queries using simple PHP syntax. In this tutorial, you’ll learn how to leverage the ‘LEFT JOIN’ SQL clause in Laravel Eloquent with multiple examples, ranging from basic to more complex scenarios.

Understanding ‘LEFT JOIN’

Before diving into Eloquent’s abstraction, let’s clarify what a ‘LEFT JOIN’ does. A ‘LEFT JOIN’ clause in SQL is used to combine rows from two or more tables, based on a related column between them, and returns all records from the left table and the matched records from the right table, filling in with NULLs if no matches are found.

Setting Up Our Environment

To follow along with these examples, ensure you have a Laravel project set up. You should have a database configured in your ‘.env’ file and have run migrations for the tables you wish to join.

Basic LEFT JOIN in Eloquent

The starting point for using joins in Eloquent is the ‘join’ method, which can be adapted to perform a ‘LEFT JOIN’. Let’s begin with a simple scenario where you have Users and Posts tables and you want to fetch all users along with their posts, if any.

// Using the query builder
$users = DB::table('users')
   ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
   ->get();

// Using Eloquent's relationship $users = User::with('posts')->get();

‘LEFT JOIN’ with Selective Columns

In reality, you may not want to select all columns from both tables. Here’s how you can select specific columns using ‘LEFT JOIN’ in Eloquent.

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

Advanced ‘LEFT JOIN’ with Where Clauses

Let’s make it a bit more complex by adding conditional clauses to filter our results.

$users = User::leftJoin('posts', function($join) {
   $join->on('users.id', '=', 'posts.user_id')
   ->where('posts.created_at', '>', now()->subDays(7));
})
->get();

‘LEFT JOIN’ with Aggregate Functions

Imagine wanting to pull all users and also know the count of posts each user has made. This requires an aggregate function, and here’s how it can be done with Eloquent.

$users = User::leftJoin('posts', 'users.id', '=', 'posts.user_id')
   ->select('users.*', DB::raw('COUNT(posts.id) as posts_count'))
   ->groupBy('users.id')
   ->get();

Multilevel ‘LEFT JOIN’

When dealing with sophisticated database schemas, you might need to perform multiple cascading ‘LEFT JOIN’ operations to fetch related data across various tables.

$users = User::leftJoin('posts', 'users.id', '=', 'posts.user_id')
   ->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
   ->select('users.name', 'posts.title', DB::raw('COUNT(comments.id) as comments_count'))
   ->groupBy('users.id', 'posts.id')
   ->get();

Conclusion

In this tutorial on using ‘LEFT JOIN’ with Laravel Eloquent, we’ve covered how to perform basic joins, select specific columns, add conditional clauses, include aggregate functions, and execute multilevel joins. The flexibility that Eloquent provides allows you to build complex queries while maintaining simplicity and elegance within your Laravel applications.