Laravel通过传递id来获得产品

时间:2017-06-29 09:06:43

标签: php mysql laravel laravel-5.4

我有一系列产品ID,我必须获取属于该ID的所有产品

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

在我的控制器中

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);
}

我将空数组作为响应

谢谢

2 个答案:

答案 0 :(得分:3)

试试这个

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

    return Response::json($products);
}

答案 1 :(得分:1)

使用whereIn

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

    return Response::json($products);
}

或者如果你想循环

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

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

    }