Recursive children with Laravel Commentable / Nested Set

I am trying to get all the recursive children using Laravel Commentable. As of now, I can get the first children like this:

$user->comments()->with(['creator', 'children.creator'])->where('parent_id', null)->get()

But this isn’t “recursive” and I’d have to do it over and over: children.children.children etc. How do I get all comments and their respective children so I can return it as JSON?

Example Output:

{
  "comments": [
    {
      "id": 1,
      "body": "foo",
      "children:" 
        {
          "id": 5,
          "body": "foo",
          "children:"
            {
              "id": 5,
              "body": "foo",
              // etc
            }
        }         
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I would try a recursive approach since you will not be certain how many children the comments will have. Just add a different method:

public function commentRecourse($model, $child = null){
    if(isset($model->child->id)){
        return $child . '.child';
    }else{
        return false;
    }
}

This would return a new relationship string like ‘children.children.children’ anytime the child has a relationship. You can call this in a loop that stops when this function returns false. Like:
loop stuff(){
  $variable[] = commentRecourse($model, $child)
}

Then you pass the variable as the with() argument.
$user->comments()->with($variable)->where.... etc.

Sorry, forgot to add that json_encoding() the array’d output will show the relationships unless you’ve messed with the $hidden model property.

Method 2

I ended up retrieving all comments $user->comments and then sorting/arranging them like this:

public static function arrange($comments)
{
    $comments->transform(function ($comment) use ($comments) {
        $comment->children = $comments->where('parent_id', $comment->id);
        return $comment;
    });

   return $comments->reject(function ($comment) {
        return $comment->parent_id !== null;
    });
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x