user11710915
user11710915

Reputation: 434

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

        }
    });

}
userRatingname(); 
</script>

Upvotes: 0

Views: 1789

Answers (3)

TsaiKoga
TsaiKoga

Reputation: 13394

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:

$products = Product::where('id','=',$id)->with('reviews.user')->get();
$data = array(); // defined the $data here out of loop
foreach ($products as $product)
{
   foreach ($product->reviews as $review){
       $data []= $review->user->name; // push the username to $data   
   }
}
// Or you can use whereIn for User:
$data = User::whereIn('id', ProductReview::where('product_id',$id)->pluck('user_id'))->pluck('name')->toArray();

return response()->json(['code' => 200, 'data' => $data]);

Change your ajax code:

function userRatingname() {
    $.ajax({
        type: "GET",
        url: '{{route('userRating.name ', $id)}}',
        success: function(data) {
            var html = '';
            data['data'].forEach(function(name) {
                html += '<div>' + name + '</div>'
            });
            $('#userRatingname').html(html);
        }
    });

Upvotes: 2

honore
honore

Reputation: 16

You have forgot to add the "csrf" tag in your ajax call

Upvotes: 0

M.Idrish
M.Idrish

Reputation: 437

try this one if its right tell me.

     $data = [];//define empty array.


    $products = Product::where('id','=',$id)->with('reviews.user')->first();


        foreach ($product->reviews as $review){
            $data[]= [$review->user->name];

        }

i understand your issue you are using variable not array so in loop u use array and use[your storing value]

Upvotes: 0

Related Questions