CamKem's avatar
Level 10

Why user relationship is returning null

Hello, I am trying to work out why the user relationship is returning null in this code:

    public function show(Thread $thread)
    {

        // if the thread viewer isn't the same as the thread owner increment the views
        if (auth()->id() !== $thread->user->id) {
            $thread->increment('views');
        }

        // get the replies & associated user
        $replies = Reply::query()
            ->select('id', 'user_id', 'body', 'created_at', 'updated_at')
            ->where('thread_id', $thread->id)
            ->with('user:username,email')
            ->latest()
            ->paginate();


        // map over the collection to be returned
        $replies->getCollection()->transform(function ($reply) {
            return [
                'body' => $reply->body,
                'created_at' => $reply->created_at,
                'updated_at' => $reply->updated_at,
                'user' => $reply->user,
            ];
        });

        return Inertia::render('Discussion/Threads/Show', [
            'thread' => [
                'title' => $thread->title,
                'body' => $thread->body,
                'slug' => $thread->slug,
                'views' => $thread->views,
                'solved' => $thread->solved,
                'repliesCount' => $thread->replies->count(),
                'user' => [
                    'username' => $thread->user->username,
                    'email' => $thread->user->email,
                    'level' => 10,
                ]
            ],
            'replies' => $replies
        ]);

    }

}

Where is say 'user' => $reply->user this returns as null. I have a relationship set up on the Reply model like this:

    public function user()
    {
        return $this->belongsTo(User::class);
    }

Can you help me figure this one out?

0 likes
2 replies
LaryAI's avatar
Level 58

The issue is that the "user" relationship is not being eagerly loaded when querying for replies. To fix this, change the "with" method call to include "user" like so:

$replies = Reply::query()
    ->select('id', 'user_id', 'body', 'created_at', 'updated_at')
    ->where('thread_id', $thread->id)
    ->with('user')
    ->latest()
    ->paginate();

This will ensure that the "user" relationship is loaded for each reply, and can be accessed as $reply->user in the transform function.

CamKem's avatar
CamKem
OP
Best Answer
Level 10

Apparently you need to eager load the id column for this to work

with('user:id,username,email')

leaving it out won't allow the relationship to load.

Please or to participate in this conversation.