Laravel Left Join Query Example Tutorial

May 25, 2021 . Admin

Laravel Left Join Query Example Tutorial

hi Dev,

In this article, I will explain 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.

Now, 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.

SQL Left Join

The LEFT JOIN returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.

You can use direct SQL LEFT JOIN in your mysql database.

Now you can use bellow sql query to copy that code and run in your mysql database.

SELECT *
FROM products
LEFT JOIN users
ON products.user_id = users.id;

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

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

    
    echo '<pre>';
    print_r($users);
    exit;
}
users Table you have to create the users table. users table products Table you have to create the products table. products table Output
    [0] => stdClass Object
            (
                [id] => 1
                [name] => john
                [price] => 45000
                [image] => 1620826541.png
                [details] => dell laptop
                [user_id] => 1
                [created_at] => 
                [updated_at] => 
                [deleted_at] => 
                [email] => man@gmail.com
                [email_verified_at] => 
                [password] => 123456
                [remember_token] => 
            )

It will help you....

#Laravel 8 #Laravel