如何检查产品是否存在laravel

时间:2019-11-02 10:17:41

标签: php laravel laravel-5

我具有此功能,用户可以在其中将产品添加到购物车。例如,这样,用户可以在某个时候卖方将产品删除后将其添加到购物车中,但仍在用户购物车中,因此,如果他签出已删除的一种产品,则会将其重定向回购物车,表示该产品已删除(一种产品效果很好),但是如果他在购物车中有两种产品,则其中一种已被删除,而另一种则没有,然后尝试检查他得到了一个错误trying to get property of non object。因此,我遍历产品ID,并检查该产品是否仍存在于数据库中,但是如果一项检查失败,但另一项检查失败,我希望将用户重定向到购物车,因此仅在没有产品的情况下签出失败。我怎样才能做到这一点 ?

控制器

public function store(Request $request)
{
    foreach (session('cart') as $productId => $item) ;
    $product = product::find($productId);
    if (!$product) {
        return redirect()->route('cart')
        }
    //Insert into orders table
    $order = Order::create([
        'shipping_email' => $request->email,
        'shipping_name' => $request->name,
        'shipping_city' => $request->city,
        'user_id' => auth()->user()->id,

    ]);

    //Insert into order product table
    if ($order) {
        $total = 0;
        foreach (session('cart') as $productId => $item) {
            if (empty($item)) {
                continue;
            }
            $product = product::find($productId);
            OrderProduct::create([
                'order_id' => $order->id ?? null,
                'product_id' => $productId,
                // $products=DB::table('products')->where('id',$id)->get();
                'quantity' => $item['quantity'],
                'Subtotal' => $item['price'] * $item['quantity'],
                'total' => $total += $item['price'] * $item['quantity'],
                'price' => $product->price,
                'name' => $product->name,
                'info' => $product->info,
            ]);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想您有模型Product,但是您正在尝试找到product

所以,尝试:

$product = Product::find($productId);

代替

$product = product::find($productId);