I’m trying to display names from the database using Ajax and I use foreach loop in the controller but it only returns one name instead of two(it doesn’t loop correctly). I have seen some answers, peoples suggested to use foreach in the view but for my case I use Ajax in the view how can I use the foreach in Ajax or is there any way it can display all names?
I have tried using these, but it was returning one name instead of two.
$data = [];
$data[] = $review->user->name;
Controller
$products = Product::where('id','=',$id)->with('reviews.user')->get();
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data = $review->user->name;
dd($data); //This returns one name
}
}
Ajax
<script >
function userRatingname() {
$.ajax({
type: "GET",
url: '{{route('userRating.name ', $id)}}',
success: function(data) {
$('#userRatingname').html('<div>' + data + '</div>');
}
});
}
userRatingname();
</script>
3
Answers
You are overwriting the value of
$data
again and again, so it will away return the last user name.You need to put the
$data = [];
out of loop. and use$data[] = $review->user->name;
inside the loop:Change your ajax code:
try this one if its right tell me.
i understand your issue you are using variable not array so in loop u use array and use[your storing value]
You have forgot to add the “csrf” tag in your ajax call