1

When user clicks on icon, ajax call to controller is called and controller returns some comments.

My controller

public function read($id)
{
    $comments = Comment::where('post_id', $id)->get();

    return response()->json([
        'html' => view('includes.comments')->render(),
        'comments' => $comments
    ]);
}

Ajax succes function

var comments_box = comments_container.find('.comments-box');
comments_box.html(data.html);
console.log(data);

In console log there is an array of objects with comments and rendered html view. But I can't iterate through that array. If i put some garbage code in comments.blade.php it shows it. But if I try @foreach($comments as $comment) some code @endforeach It can't work at all, error message is Undefined variable: comments

2 Answers 2

1

you need to pass the variable to the view (if you want to use that variable in the blade file)

for example by saying

return view('includes.comments', ['comments' => $comments]);

that way the $comments variable will be available in the blade file and you can then use the @foreach

more on views documentation

Sign up to request clarification or add additional context in comments.

Comments

1

I believe instead of:

return response()->json([
    'html' => view('includes.comments')->render(),
    'comments' => $comments
]);

you should rather use:

return response()->json([
    'html' => view('includes.comments', ['comments' => $comments])->render(),
    'comments' => $comments // this line might be not necessary
]);

This is because you want to render blade and you need to pass $comments into view. So depending on what you really want to return as json line:

'comments' => $comments // this line might be not necessary

might be completely not necessary in case you wanted to use it for view.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.