Using "With" Method
Imagine having a "post" controller and you want to eager load the "comments" relation. You can achieve it like below.
# app/Http/Controllers/PostController.php public function show(int $postId) { $postWithComments = Post::with('comments')->findOrFail($postId); dd($postWithComments); }
Using "Load" Method
Or if you are using route model binding then you can make use of the "load" method of the model instance.
# app/Http/Controllers/PostController.php public function show(Post $post) { $postWithComments = $post->load('comments'); dd($postWithComments); }
Nested Relation
If you have a nested relation then you can make use of the "dot" character to call the nested relationship. For example "post" has many "comments" and each of the comments has many "likes" then you can define it like below
# app/Http/Controllers/PostController.php public function show(Post $post) { $postWithCommentsAndLikes = $post->load('comments.likes'); dd($postWithComments); }
Leave a reply