DomainFlag
DomainFlag

Reputation: 564

Threaded Comments, php, laravel

This is my table NewTheme_Comment:

    id
    parent_id
    id_theme
    user
    text
    upVotes
    downVotes

And this is my controller:

class Comments extends Controller {

public function GenerateComments($id){
    $Comments = NewTheme_Comment::where('id_theme',  $id)->paginate(5);
    return view('comments', ['Comments'=>$Comments]);
}

Id is the link to the general post(each posts have different section of comments), so dynamically at the click of user, user is redirected to the ('comments view') section of comments accordingly.

So I have the array Comments which is populated with the values from the table NewTheme_Comment, the problem for me consists of how can I use the values to create a Threaded Comments section.

Like so in my view(the problem is that this makes a comment section as like as every parent_id is equal to 0 which is not that I am looking for:

 @foreach ($Comments as $Comment) {{-- Comments threads --}}

<div class="media">
  <div class="media-left">
  </div>
  <div class="media-body">
    <p class="media-heading">{{ $Comment->text }}</p>
    <p class="media-heading">{{ $Comment->user }} / {{ $Comment->created_at }} </p>
  </div>
</div>


@endforeach {{-- Comments threads --}}

The end result:

0 
1
2
3
2
1
1
0
1
0

My idea is to make comments like(with parent_id):

   0
     1
      2
       3
      2
     1
     1
   0
     1
   0

But I can't find the right way to do this thing logically, so that in the end to look like a simple threaded comment section the same that reddit uses( for my little web application ).

If my approach is bad, I would greatly appreciate other better ways on how to solve this.

Upvotes: 0

Views: 853

Answers (2)

Huzaib Shafi
Huzaib Shafi

Reputation: 1138

It is a multi-step solution. You should prefer using lazychaser/laravel-nestedset package as the threaded comment is a form of nested set.

The other way round, if you want to continue with your current approach, will be having child function in your Comment Model, as follows

public function children(){
   return $this->hasMany('App\Models\Comment', 'parent_id'); //Change as per your application architecture
}

Then in views, you can check for the children of a given node by calling a partial view recursively, containing

//print the details of $Comment
@foreach($Comment->children as $childComment)
   //call this partial view again for $childComment & print the details
@endforeach

Upvotes: 2

Martin
Martin

Reputation: 1171

List every comment that doesn't have a parent_id, then when you load your comments check if any of those comments have childs comments and list those with indentation.

Upvotes: 1

Related Questions