Posts Learn Components Snippets Categories Tags Tools About

Laravel with relationship but use join syntax

Learn how to get model relationship in laravel but using join instead

Created on Aug 06, 2021


Query Relationship using with()
To easily get the model relationship in Laravel, you can make use of the "with()" method of the model class and specify the relationship instance to be retrieved.

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

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

But the query above has some downside which is querying the database twice since it's retrieving the "posts" table first and then the "comments" table relation. In big-scale applications, the code above will be inefficient.

Query Relationship using Join
To replicate the query code like above but only querying the database once, then you can write it using the join clause.

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


By writing it like above it's much more efficient and you will get the same result as using the "with()" method.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel with relationship but use join syntax