LARAVEL: I am only getting one item from my table when there are multiple items. How would I get all of them and output them?

  database, laravel, php, session

I am using a session to create a basic cart. In the session there are multiple IDs ranging from 1-3.

When I output the data using foreach it only outputs the first item from the table. I would like all the related items to appear. How would I go about doing that?

Here is my index function from my controller:

public function index()
{
    session_start();
    $cartData = implode(',', $_SESSION['cart']);
    $cartProducts = Product::where('id',$cartData)->get();
    return view('basket',['cartProducts'=>$cartProducts ],['cartData' =>$cartData] );
}

This is my output on the cart page:

  @foreach($cartProducts as $cartProduct)


         <p>{{$cartProduct->name}}</p>
         <p>{{$cartProduct->size}}</p>
         <p>{{$cartProduct->price}}</p>

  @endforeach

And for testing purposes this is my dump and die of the $cartData:

"1,1,3"

And finally this out the actual output:

Original

small

8

Source: Laravel

Leave a Reply