Running where() more more than one time

Adarsh Kumar :

Question: How can I run the where query for all rows in $cart, instead for just $cart[0], or [1] or [2].

I am trying to manually code a Shopping Cart in Laravel. Since I am a novice, I am stuck at a point. Please take a look at the code below:

public function showCart()
{
    $user = Auth::user();
    $cart = Cart::where('user_id', $user->id)->get();
    $product = Products::where('id', $cart[0]->product_id)->get();
    return view('showCart')
           ->with('cart', $cart)
           ->with('user', $user)
           ->with('product', $product);
}

This is my function to show a user's cart. Here, I am trying to show all the products that a user has in his cart, and also send a variable with the product details.

However, while I am trying to send all the products in the user's cart as a $product array, I am only getting the first product. That is because the rows returned in $cart is more than one, but I am unable to write a query for getting all the products in this line:

$product = Products::where('id', $cart[0]->product_id)->get();

. . . because, quite clearly, I am writing a query to match only the first row returned in $cart.

Thanks in Advance.

DigitalDrifter :

You can use the whereIn and the data_get helper function:

$product = Products::whereIn('id', data_get($cart, '*.product_id'))->get();

data_get works with both arrays and objects. Alternatively, you can use Arr::get for arrays only.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related