Brandon
Brandon

Reputation: 1081

Nested comments with Laravel

I'm currently trying to replicate something similar to a forum, but I'm stumped on how I could create nested comments. I understand that for regular replies I could create a replies table and run a loop for each comment that matches the thread id. But I don't know how I would easily do this for nested replies.

Could someone please give me some advice or point me in the right direction? Thanks.

This is the structure for my posts table:

Screenshot of phpMyAdmin http://bitdrops.co/drops/J5v.png

Upvotes: 2

Views: 2873

Answers (1)

whoacowboy
whoacowboy

Reputation: 7447

You want to look into polymorphic relations to solve this. You want to be able to comment on Posts and Comments.

What I have done is set up a commentable trait and have the models I want to add comments to use it. This way if you ever want to comment on another model, you can just add the trait to that model.

Laracasts is a great resource for laravel and has a good lesson on traits.

There is a bit more to it than this, but hopefully it will get you started.

You set up your database structure like this.

User Table

  `id` int(10),
  `name` varchar(255),
  `username` varchar(255)

Comments table

  `id` int(10),
  `user_id` int(10),
  `body` text,
  `commentable_id` int(10),
  `commentable_type` varchar(255)

Posts Table

  `id` int(10),
  `user_id` int(10),
  `body` text

Your models like this.

Comment Model

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

    use CommentableTrait;

    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Post Model

<?php namespace App;

use CommentableTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    use CommentableTrait;

}

and of course you need the trait.

Trait

<?php namespace App;

use Comment;

trait CommentableTrait {

    /**
     * List of users who have favorited this item
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function comments()
    {
        return $this->morphMany('App\Comments\Comment', 'commentable')->latest();
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addComment($body, $user_id)
    {

        $comment = new Comment();
        $comment->body = $body;
        $comment->user_id = $user_id;

        $this->comments()->save($comment);

        return $comment;
    }

}

Upvotes: 8

Related Questions