dante dante - 5 months ago 48
PHP Question

PHP Comment System using Laravel

I am developing a website using laravel PHP and trying to do a comment system using the following structure:

- Comment 1 (id = 1)
-- Reply 1 (id = 2) (parent_id = 1)
--- Reply 2.1 (id = 3) (parent_id = 2)
-- Reply 2 (id = 4) (parent_id = 1)


I am wondering how would I do a foreach to cover that? Since i don't know how many child comments a comment will have.

Answer
Table Like:

+------------+-----------+---------+
| comment_id | parent_id | comment |
+------------+-----------+---------+
|          1 |         0 | test    |
|          2 |         1 | test1   |
|          3 |         0 | test2   |
|          4 |         0 | test3   |
|          5 |         1 | test4   |
|          6 |         2 | test4   |
|          7 |         4 | test5   |
|          8 |         5 | test6   |
|          9 |         6 | test7   |
|         10 |         4 | test8   |
|         11 |         3 | test9   |
+------------+-----------+---------+


Get first level parent:

$comments = Comment::where('parent_id', '0')->orderBy('comment_id', 'asc')->get();

$result = array();
foreach($comments as $comment){
    $list = array();
    $list = array_merge($list, [['comment_id' => $comment->comment_id, 'parent_id' => $comment->parent_id, 'comment' => $comment->comment]]);
    $result = array_merge($result, $this->get_child_comment($comment->comment_id,0, $list));
}


function get_child_comment($pid,$level,$list=array()) {
        $sub_comments = Comment::where('parent_id','=',$pid)->where('comment_id','!=',$pid)->orderBy('comment_id', 'asc')->get();        
        foreach($sub_comments as $sub_comment){
            $space=" "; sigm='-';
            for($j=0; $j<=$level; $j++)
            {
                $space .=$space;
            }
            for($j=0; $j<=$level; $j++)
            {
                $space .= $sigm;
            }
            $sub_comment->comment = html_entity_decode($space, ENT_QUOTES, "utf-8").' '.$sub_comment->comment;

            $list = array_merge($list, array(['comment_id' => $sub_comment->comment_id, 'parent_id' => $sub_comment->parent_id, 'comment' => $sub_comment->comment]));

            $list = $this->get_child_comment($sub_comment->comment_id, $level+1, $list);
        }
       return $list;
    }
}


return get array.simple print using foreach:
foreach($result as $val) {
    echo $val['comment'].'<br>';
}

Output:

test

  - test1

    -- test4

        --- test7

  - test4

    -- test6

test2

  - test9

test3

  - test5

  - test8