this is a relation can not return null
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.
Please or to participate in this conversation.