In this tutorial you will learn about the Laravel Eloquent Join 2 Tables Example and its application with practical example.
In this Laravel eloquent join 2, 3, or multiple tables example I’ll show you how to use laravel eloquent join with 2 or multiple tables for fetching data from multiple tables. In this laravel join tutorial you will also learn how to use laravel eloquent join() with multiple where conditions.
Laravel Eloquent Join
In laravel model when you want to fetch data from multiple table with associated relationship In that case you can fetch data using laravel joins. In laravel as per the need we have to use left join(), right join(), cross join() or to join two or multiple table.
Laravel Eloquent Join() with 2 Tables
Let suppose you want to fetch data using laravel eloquent join(), from 2 table, then you can do it as following:
1 2 |
$users = User::join('posts', 'users.id', '=', 'posts.user_id') ->get(['users.*', 'posts.descrption']); |
The above given join query you will get the following SQL query:
1 2 |
select `users`.*, `posts`.`descrption` from `users` inner join `posts` on `users`.`id` = `posts`.`user_id` |
Laravel Eloquent Join() with 3 Tables
Let suppose you want to fetch data using laravel eloquent join(), from 2 table, then you can do it as following:
1 2 3 |
$users = User::join('posts', 'posts.user_id', '=', 'users.id') ->join('comments', 'comments.post_id', '=', 'posts.id') ->get(['users.*', 'posts.descrption']); |
The above given join query you will get the following SQL query:
1 2 3 |
select `users`.*, `posts`.`descrption` from `users` inner join `posts` on `posts`.`user_id` = `users`.`id` inner join `comments` on `comments`.`post_id` = `posts`.`id` |
Laravel Eloquent Join() with Multiple Conditions
Suppose now you want to get data using laravel eloquent join with multiple where conditions, you can use laravel eloquent join as following:
1 2 3 4 |
$users = User::join('posts', 'posts.user_id', '=', 'users.id') ->where('users.status', 'active') ->where('posts.status','active') ->get(['users.*', 'posts.descrption']); |
The above given join query you will get the following SQL query:
1 2 3 |
select `users`.*, `posts`.`descrption` from `users` inner join `posts` on `posts`.`user_id` = `users`.`id` where `users`.`status` = active and `posts`.`status` = active |