سلام دوستان من این کدو نوشتم ارور میده باید چطوری بنویسم که ارور نده
$shoppingCart = $this->shoppingCart->where('product_id', $product->id)->first();
$shoppingCart->updateOrCreate([
'product_id' => $product->id,
'user_id' => $this->user_id,
'purchase_code' => \Str::random(10),
'price' => $this->price,
'total_price' => $this->price,
], [
'quantity' => $shoppingCart->quantity + $quantity,
'total_price' => $this->price * ($shoppingCart->quantity + $quantity)
]);
ارور این میده
Call to a member function updateOrCreate() on null سلام من از بیرون فقط ایدی محصول میگیرم و تعداد محصول این کدی که نوشتم میخوام خلاصه ترش کنم
این کد اجرا میشه کاملا
if ($shoppingCart = ShoppingCart::where('product_id', $product->id)->first()) {
if (($shoppingCart->quantity + $quantity) <= $product->inventory) {
$shoppingCart->update([
'quantity' => $shoppingCart->quantity + $quantity,
'total_price' => $this->getPrice($product) * ($shoppingCart->quantity + $quantity)
]);
}
} else {
ShoppingCart::create([
'product_id' => $product->id,
'user_id' => $this->user_id,
'purchase_code' => \Str::random(10),
'quantity' => $quantity,
'price' => $this->getPrice($product),
'total_price' => $this->getPrice($product) * ($quantity)
]);
}
این کدتون خیلی اشتباس، می تونید از if خلاصه شده استفاده کنید.
https://davidwalsh.name/php-ternary-examples
شاید پاسخ شما همینجا باشد
این روش الان درسته ؟
$shoppingCart = ShoppingCart::where('product_id', $product->id)->first();
return $shoppingCart && ($shoppingCart->quantity + $quantity) <= $product->inventory ?
$shoppingCart->update([
'quantity' => $shoppingCart->quantity + $quantity,
'total_price' => $this->getPrice($product) * ($shoppingCart->quantity + $quantity)
]) :
ShoppingCart::create([
'product_id' => $product->id,
'user_id' => $this->user_id,
'purchase_code' => \Str::random(10),
'quantity' => $quantity,
'price' => $this->getPrice($product),
'total_price' => $this->getPrice($product) * ($quantity)
]);
$shoppingCart = $this->shoppingCart->where('product_id', $product->id)->first();
$shoppingCart->updateOrCreate([
'product_id' => $product->id,
'user_id' => $this->user_id,
'purchase_code' => \Str::random(10),
'price' => $this->price,
'total_price' => $this->price,
], [
'quantity' => $shoppingCart->quantity + $quantity,
'total_price' => $this->price * ($shoppingCart->quantity + $quantity)
]);
به این روش نوشتم
@samanzdev
خالی نیست فقط پروداکت ایدی میگیرم
بقیه خودم تعریف کردم اگر خالی باشه کدی که من نوشتم بالا نشون دادم کار نمیکرد درصورتیکه کار میکنه
@samanzdev