Laravel Left Join Query Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

1865

09-01-2020


hi guys,

In this tutorial, I will learn you to use left join query builder in laravel project. i will write simple left join query using laravel query builder. we will use db(), join() to write left join query in laravel.

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

In this example, i will create two tables users and user_details. i will display to user_id field in user_details table.

left join query builder

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$users =DB::table('users')

->leftJoin('user_details', 'users.id', '=', 'user_details.user_id')

->get();

echo '<pre>';

print_r($users);

exit;

}

users Table

you have to create the users table.

user_details Table

you have to create the user_details table.

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

)

It will help you....


Recommended Posts