How to use Left Join Query in Laravel ?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Laravel Left Join Query Example

Today now here in this post, I will show you how to use left join query builder in laravel 8 project. So here i will write a simple left join query by using laravel query builder. So here we can use db(), join() to write left join query in laravel application.

Now in the first argument will passed to the join method is the name of the table you need to join to, while the remaining arguments will specify the column of constraints for the join. So we can even join to multiple tables in a single query.

Now in this example, i will create two table one is users and another one is  user_details. So here i will display to user_id field in profiles table.

left join query builder

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    
    $users =DB::table('users')
            ->leftJoin('profiles', 'users.id', '=', 'user_details.user_id')
            ->get();

    
    echo '<pre>';
    print_r($users);
    exit;
}

users Table

you have to create the users table.

Laravel Left Join Query Example
Profiles table
Laravel Left Join Query Example

Output

Array(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => mehul
            [age] => 29
            [email] => bagadamehul@gmail.com
            [email_verified_at] => 
            [password] => 123456
            [type] => 1
            [votes] => 101
            [remember_token] => 
            [created_at] => 2019-12-27 00:00:00
            [updated_at] => 
            [user_id] => 3
            [mobile] => 7046796365
            [address] => test address 1
            [pincode] => 360012
        )

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →