Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel Left Join Query Example

Laravel Left Join Query Example

Laravel left join query example; In this tutorial, we would like to share with you in detail about laravel left join. And also how to use laravel left join with multiple where conditions.

Note that, data has to be fetched from more than one table. At that time the joins are used in laravel.

If you are using laravel left join eloquent with a query builder, At that time, laravel left join fetch data from the left table. Even if there is no match in the right table. So the result is null from the right side.

Laravel Left Join Examples

Laravel LEFT JOIN eloquent returns all rows from the left table, even if there are no matches in the right table, The result is NULL from the right side.

Let’s understand of laravel left join, suppose you have two 2 tables in the database. One is a posts table and the other is an authors table.

And when you get the data from the authors table. And left join posts with authors table. At this time, the details of the author will be get with posts collection. And if the no posts of authors in posts table. So the collection of posts will get null with all the details of the author.

And if there are author posts in the posts table, then data will get from both tables.

Now learn laravel left join query in laravel, see the following examples one by one:

Example 1: Laravel Left Join Query

Here, fetch data using laravel left join with authors and posts table, you can see the following example:

 Author::leftJoin('posts', 'posts.author_id', '=', 'authors.id')
       ->select('authors.*')
       ->get();

When you dump the above-given laravel left join query, you will get the following SQL query:

select `authors`.* from `authors` 
left join `posts` on `posts`.`author_id` = `authors`.`id`

Example 2: Laravel Left Join with Multiple Condition

In this example, get data using laravel left join with multiple where conditions on authors and posts table, you can see the following example:

Author::leftJoin('posts', 'posts.author_id', '=', 'authors.id')
       ->select('authors.*')
       ->where('authors.status', 'active')
       ->where('authors.subscription', 'active')
       ->get();

When you dump the above-given laravel left join with multiple conditions query, you will get the following SQL query:

select `authors`.* from `authors` 
left join `posts` on `posts`.`author_id` = `authors`.`id` 
where `authors`.`status` = active and `authors`.`subscription` = active

Conclusion

Laravel left join tutorial, you have learned how to use laravel left join and as well as how to use left join with multiple condition.

More Laravel Posts

Recommended:-Laravel Try Catch

RELATED ARTICLES

Most Popular

Recent Comments