Prevent using ->with() when relationship is already fetched

Posted 3 years ago by canfiax

I find it strange that I'll have to use ->with() on relationships that is already fetched, to prevent a lot of queries. Let me give you an example:

 * A lot of queries
 * @var [type]

    $post = Post::find(1);

    foreach($post->comments as $comment) {
        echo $comment->text . ' on post ' . $comment->post->name; // calling $comment->post will cause an extra query

I know I can eager load, but that still feels unnecessary since I already have the $post data above.

 * Prevent a lot of extra queries

    $post = Post::find(1);

    foreach($post->comments()->with('post')->get() as $comment) {
        echo $comment->text . ' on post ' . $comment->post->name; // this solves my issue, $post is only fetched ONCE. However, it would be more cool if laravel knew that $comments has a $parent called $post, so I would not need to eagerload using ->with('post').

This example is extremely simplified. In above example, I could just do:

echo $comment->text . ' on post ' . $post->name;

However, there are many situations, where you don't have directly access to $post (i.e. when using Transformers, or other more complex situations).

What I would like to achieve is for the $comment to have a parent called $post so it won't fetch twice when using $comment->post

Please sign in or create an account to participate in this conversation.