Support the ongoing development of Laravel.io →
posted 6 years ago

I have this function:

public function show($id)

    {

        if (count($post = Post::find($id))) {

            $post = $post->load(['comments' => function ($q) {
                $q->latest();
                $q->with(['author' => function ($q) {

                    $q->select('id', 'username');

                }]);
            }, 'user' => function ($q) {

                $q->select('id', 'username');

            }]);

            $this->authorize('seePost', $post);

            return view('post.show', ['post' => $post]);

        } else {

            dd('no post');
        }

    }

I added the if statement as if I try to open a route to a non existent post id I get the error Call to a member function load() on null. However now I have two queries, one looks for the Post in the DB and if it finds one then I have to load the relations with the second one. What can I do to go back to just one query with all the relations loaded and avoid the error? Any clue?

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

chriz74x chriz74x Joined 8 Apr 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.