35 lines
862 B
PHP
35 lines
862 B
PHP
<?php
|
|
|
|
namespace App\Actions\Cart;
|
|
|
|
use App\Data\Cart\AddToCartDTO;
|
|
use App\Data\Cart\CartDTO;
|
|
use App\Models\User;
|
|
use InvalidArgumentException;
|
|
|
|
final readonly class UpdateProductInCartAction
|
|
{
|
|
/**
|
|
* Execute the action.
|
|
*
|
|
* @throws InvalidArgumentException
|
|
*/
|
|
public function execute(AddToCartDTO $cartData, User $user)
|
|
{
|
|
$cart = $user->carts()->active()->sole();
|
|
|
|
$productInCart = $cart->products()->find($cartData->productId);
|
|
|
|
throw_if($productInCart === null, new InvalidArgumentException('Product not found'));
|
|
|
|
$cart->products()->updateExistingPivot($cartData->productId, [
|
|
'quantity' => $cartData->quantity,
|
|
]);
|
|
|
|
return CartDTO::fromModel($cart->load(['products' => function ($query) {
|
|
$query->withPivot('quantity', 'price');
|
|
}]));
|
|
|
|
}
|
|
}
|