'Laravel - foreach on collection
I have a request :
$comments = $post->comments()->with('replyComments:id,post_id,user_id,content,created_at,reply_comment_id')->orderBy('created_at', 'desc')->get();
When i try to echo this with a foreach, i have :
foreach ($comments as $comment) {
echo $comment;
};
Result :
{"id":383825,"post_id":553304,"user_id":6,"content":"test","created_at":"2022-04-28 15:16:19","reply_comment_id":null,"reply_comments":[{"id":383826,"post_id":553304,"user_id":6,"content":"reply test","created_at":"2022-04-28 16:20:16","reply_comment_id":383825}]}
But if i do :
foreach ($comments as $comment) {
echo $comment->replyComments; /* or $comment->reply_comments; */
};
The result is NULL
How could i echo reply_comments ?
Thanks for your help !
EDIT FOR MORE DETAILS :
$comments = $post->comments()->with('likes','replyComments')->orderBy('created_at', 'asc')->get(['id','post_id','user_id','content','created_at','reply_comment_id']);
foreach($comments as $comment){
dd($comment);
}
$comments = $post->comments()->with('likes','replyComments')->orderBy('created_at', 'asc')->get(['id','post_id','user_id','content','created_at','reply_comment_id']);
foreach($comments as $comment){
dd($comment->likes);
}
$comments = $post->comments()->with('likes','replyComments')->orderBy('created_at', 'asc')->get(['id','post_id','user_id','content','created_at','reply_comment_id']);
foreach($comments as $comment){
dd($comment->replyComments);
}
About likes and replyComments, in Comment.php :
public function replyComments()
{
return $this->hasMany(self::class, 'reply_comment_id', 'id');
}
public function likes()
{
return $this->hasMany(\App\CommentLike::class, 'comment_id', 'id');
}
Solution 1:[1]
If you want to display the replies in one level like Youtube does, you need using the following query:
$post = Post::with('comments.replyComments')->find($id);
$comments = $post->comments;
$replies = $comments->replyComments;
Solution 2:[2]
reply_comments OR replyComments are not present in the output JSON. Hope you missed it on fetching!
$comments = $post->comments()->with('replyComments:replyComments')->orderBy('created_at', 'desc')->get();
This needs to add to the fetch code.
then
foreach ($comments as $comment) {
echo $comment->replyComments;
};
Or else you can use array.
displayData = [];
foreach ($comments as $comment) {
displayData[] = $comment->replyComments;
};
echo displayData;
Solution 3:[3]
use print_r($comment->replyComments) instead of echo.
Solution 4:[4]
`$comment->replyComments` is an array and you should put it in foreach:
foreach($comment->replyComments as $item){
echo $item;
}
or write:
echo $comment->replyComments[0];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
| Solution 2 | ABHILASHA K.M |
| Solution 3 | Sarfaraz khan |
| Solution 4 | amirhosein hadi |



