Laravel Left Join Eloquent Query Example

Throughout this Laravel Left Join Eloquent Query Example tutorial you will learn how to use left join query builder in laravel application to get relational data.

 Laravel itself provide inbuilt method to left join the table like in MySQL or SQL based database we can do join multiple tables using leftJoin function. Left join should use same as join, in leftjoin the primary (parent) tables return all time if or not child table have records.

Left Join Query Builder

You just add LeftJoin query builder for getting the relational table records just like below:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::leftJoin('user_details', 'users.id', '=', 'user_details.user_id')->get();
        echo '<pre>'; print_r($users); die;
    }
}

Users Table

Your parent (users) table should be look like this:

user_details Table

Your child (user_details) table should be look like this:

Output

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Test 1
            [email] => test001@gmail.com
            [email_verified_at] => 
            [created_at] => 2021-07-17T19:13:54.000000Z
            [updated_at] => 2021-07-17T19:13:54.000000Z
            [first_name] => Test
            [last_name] => Demo
            [user_id] => 1
            [city] => Mohali
            [state] => Punjab
            [pincode] => 160105
            [country] => India
        )

    [1] => Array
        (
            [id] => 2
            [name] => Test 2
            [email] => test002@gmail.com
            [email_verified_at] => 
            [created_at] => 
            [updated_at] => 
            [first_name] => Test
            [last_name] => Two
            [user_id] => 2
            [city] => Chandigarh
            [state] => Chandigarh
            [pincode] => 160069
            [country] => India
        )

)

I hope this will work for you.

Leave a Comment