samedi 2 novembre 2019

How to check if product exists or not laravel

I have this functionality where user can add product to cart. e.g so user can add one product in cart after sometime the product gets deleted by the seller but still it is in the users cart, so if he checks out one product which has been deleted it will redirect him back to cart saying the product was deleted(one product works fine) but if he has two products in the cart one has been deleted and the other has not, and tries to check out he gets an error trying to get property of non object. So I'm looping over the product ids and checking if the product still exists in the database, but if that check fails for one, but not another I want the user to be redirected to the cart, so it should only checkout if no product fails. How can I do this ?

Controller

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


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire