Mile Panic Mile Panic - 3 years ago 266
Ajax Question

Laravel: can't iterate through array of objects from json

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');

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download