php - 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?

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
Answer
Solution:
You have two issues:
- You're passing in a string of IDs instead of an array
{-code-1}
only looks for a single value.
So the query is actually becoming{-code-1} id = '1,1,3'
, which may only match the id of1
. To fix it, pass in the actual array, and use{-code-1}In
:
Product::{-code-1}In('id', $_SESSION['cart'])->get();
This changes the query to{-code-1} id IN (1,1,3)
.
Answer
Solution:
You are just using where, which is not helpful on what you are trying to achieve.
You should rather be using whereIn (equivalent to wherein() in sql) without imploding (use array directly).
->whereIn('id', $cartData)
This should solve your problem.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: deprecated: directive 'allow_url_include' is deprecated in unknown on line 0
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.