mardi 24 mars 2020

Foreach in Controller returns Only one Output Laravel and Ajax

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: '',
        success: function(data) {
            $('#userRatingname').html('<div>' + data + '</div>');

        }
    });

}
userRatingname(); 
</script>


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire