PHP Laravel Join Query Example

Today, We want to share with you join query in laravel.In this post we will show you laravel left join multiple conditions, hear for used belongsTo(), you can use hasOne, hasMany as you need we will give you demo and example for implement.In this post, we will learn about Laravel 6 right join query Example Tutorial with an example.

PHP Laravel Left Join Query Example

SQL Query:

select `members`.`id`, `members`.`name`, `members`.`email`, `locations`.`name` as `location_name` 
	from `members` 
	left join `locations` on `locations`.`id` = `members`.`location_id`

Laravel Query:

leftJoin("locations", "locations.id", "=", "members.location_id")
                        ->get();
  
        dd($members);
    }
}

Results

Array

(

    [0] => Array

        (

            [id] => 1
            [name] => Prof. Chirag Prajapati JD
            [email] => [email protected]
            [location_name] => IN

        )

    [1] => Array

        (

            [id] => 2
            [name] => Mr. Meet Parmara
            [email] => [email protected]
            [location_name] => US

        )

    [2] => Array

        (

            [id] => 3
            [name] => Raghav Domadiya
            [email] => [email protected]
            [location_name] => CA

        )

    [3] => Array

        (

            [id] => 4
            [name] => Miss Parag Shukla J
            [email] => [email protected]
            [location_name] => 

        )

)

Example: Using Relationship

app/Member.php

 'datetime',
    ];
  
    /**
     * Get the comments for the blog post.
     */
    public function location()
    {
        return $this->belongsTo(Country::class);
    }
}

app/Country.php


Laravel Query:

with('location')
                        ->get();
  
        foreach ($members as $key => $value) {
            echo $value->id;
            echo $value->name;
            echo $value->location->name ?? '-';
        }
        dd($members);
    }
}

I hope you get an idea about laravel subquery.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment