Mr Robot
Mr Robot

Reputation: 897

Laravel get products by passing id

I have an array of products id, i have to fetch all the products belonging to that id

{
    "products":[1,2,3,4,5,6]
}

in my controller

public function productsCart(Request $request) 
{
    //dd($request->products);

    foreach ($request->products as $key => $product) {

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

    }

    return Response::json($product);
}

i'm getting empty array as response

thank you

Upvotes: 0

Views: 2576

Answers (2)

Rahul
Rahul

Reputation: 2474

Use whereIn

public function productsCart(Request $request) 
{
    $products = Product::whereIn('id', $request->products)->get();

    return Response::json($products);
}

or if you want to loop then

foreach ($request->products as $id) {

        $product[] = Product::where('id', $id)->get();

    }

Upvotes: 1

Zayn Ali
Zayn Ali

Reputation: 4925

Try this

public function productsCart(Request $request) 
{
    $products = Product::whereIn('id', $request->products)->get();

    return Response::json($products);
}

Upvotes: 3

Related Questions