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
Advertisement
Answer
You have two issues:
- You’re passing in a string of IDs instead of an array
where
only looks for a single value.
So the query is actually becoming where id = '1,1,3'
, which may only match the id of 1
. To fix it, pass in the actual array, and use whereIn
:
Product::whereIn('id', $_SESSION['cart'])->get();
This changes the query to where id IN (1,1,3)
.