Fredi
Fredi

Reputation: 159

Laravel 5.8: MorphMany relation returns Empty

Comment Model:

public function commentable()
{
    return $this->morphTo();
}

public function comments()
{
    return $this->hasMany(Comment::class , 'parent_id' , 'id');
}

public function setCommentAttribute($value)
{
    $this->attributes['comment'] = str_replace(PHP_EOL , "<br>" , $value);
}

Post Model:

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

And Controller:

public function show_comments(Post $post)
{
    $comments = $post->comments()
                ->where('approved' , 1)
                ->where('parent_id', 0)
                ->latest()
                ->with(['comments' => function($query) {
                    $query->where('approved' , 1)->latest();
                }])->get();

    dd($comments);
    return view('post',compact('comments'));
}

Database table Comments:

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('parent_id')->unsigned()->default(0);
            $table->boolean('approved')->default(0);
            $table->text('comment');
            $table->integer('commentable_id')->unsigned();
            $table->string('commentable_type');
            $table->timestamps();
        });

$dd($comments) returns #items: [] or Empty. There are database records and I can access them with another methods.

I did searching alot before asking but no luck.

Upvotes: 1

Views: 961

Answers (1)

Sergio Opale
Sergio Opale

Reputation: 21

I was trying to resolve the same issue for a few hours. For anyone searching for the answer :

Check if the commentable_type field in comments table has properly formatted route strings

'commentable_type' => 'App/Models/Comment',       // Does not work

'commentable_type' => 'App\Models\Comment',      // Works 🥳

Upvotes: 2

Related Questions