Laravel Eloquent Join Multiple Table Query Example

Hello Artisan,

In this tutorial, I will show you how to join tables in Laravel using Laravel eloquent. We know the join query using the query builder. But in this example, I will show you how we can join 2 or more then 2 tables which means multiple tables with Laravel eloquent.

You know that this query gives us better performance than the eager loading query. So I will show you laravel eloquent join 2 tables and also laravel eloquent join 3 tables with query example:

See the below example:

$post = Post::with('comments')->first();

dd($post->comments); // get all of the comments relation

 

Laravel Eloquent Join() with 2 Tables

In this example, we will see the join example with laravel eloquent with 2 tables. get data using laravel eloquent join 3 tables, you can see the following example:

We can write this above equivalent query like :

$post = Post::join('comments', 'posts.comment_id', '=', 'comments.id')->first();

dd($post->comments);

 

Laravel Eloquent Join() with 3 Tables

In this example, we will see the join example with laravel eloquent with 3 tables. get data using laravel eloquent join 3 tables, you can see the following example:

$users = User::join('posts', 'posts.user_id', '=', 'users.id')
              ->join('comments', 'comments.post_id', '=', 'posts.id')
              ->get(['users.*', 'posts.descrption']);

 

Read also: Subquery Joins Example in Laravel

 

Hope this laravel eloquent join multiple conditions query example will help you.

 

#laravel #laravel-9x #laravel-tips #eloquent-tips