Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheRealMkadmi's avatar

Querying nullable BelongsTo through MorphOne

I'm trying to write a code for finding the latest commenter and last commented at properties for a Commentable model.

Those models may or may not have comments, and I'm trying to display them in the index/detail view of Nova.

I tried fetching the latest comment via ->latestOfMany() checking for existence through the ->exists() method, but I'm not sure what to return if the model hasn't been commented yet.

Here's the full trait used:

<?php

namespace App\Traits;

// extension over KirschbaumDevelopment\NovaComments\Commentable
use KirschbaumDevelopment\NovaComments\Commentable;
use KirschbaumDevelopment\NovaComments\Models\Comment;

trait HasComments
{
    use Commentable;

    public function latestComment(): \Illuminate\Database\Eloquent\Relations\MorphOne
    {
        return $this->morphOne(Comment::class, 'commentable')->latestOfMany();
    }

    public function latestCommenter(): ?\Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        $latestComment = $this->morphOne(Comment::class, 'commentable')->latestOfMany();
        if($latestComment->exists()){
            return $latestComment->commenter();
        } else {
            return null; // <-- problematic line
        }
    }

    public function getLastCommentedAtAttribute()
    {
        $latestComment = $this->morphOne(Comment::class, 'commentable')->latestOfMany();
        if($latestComment->exists()){
            return $latestComment->get("created_at");
        } else {
            return null; // <-- problematic line
        }
    }

}

In its current form, called like this:

BelongsTo::make('Last Commenter', 'latestCommenter', User::class)->nullable()

it spits out the following error:

"message": "Call to a member function withoutGlobalScopes() on null",
"exception": "Error",
"file": "<path>/vendor/laravel/nova/src/Fields/BelongsTo.php",
"line": 182

Probably a mild case of RTFM, but I still can't figure it out, or if it's even supported by Nova.

0 likes
2 replies
khaledw62's avatar

you may return a nullable builder but you can not return null, i did not work with nova before but it seems to accept only relation so you can just return it and if it was null, is there any error happen or what?

    public function latestCommenter(): BelongsTo
    {
        return $this->morphOne(Comment::class, 'commentable')->latestOfMany();
    }
1 like

Please or to participate in this conversation.