- schema for cart and product - define relationship, DTO, Resource and API collections - Add post and get endpoint for cart api
47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Data\AddToCartDTO;
|
|
use App\Data\CartDTO;
|
|
use App\Enums\CartStatus;
|
|
use App\Models\Product;
|
|
use App\Models\User;
|
|
|
|
final readonly class AddProductToCartAction
|
|
{
|
|
/**
|
|
* Execute the action.
|
|
*/
|
|
public function execute(AddToCartDTO $cartData, User $user)
|
|
{
|
|
$cart = $user->carts()->active()->firstOrCreate([
|
|
'status' => CartStatus::Active,
|
|
]);
|
|
|
|
$price = Product::query()->whereId($cartData->productId)->value('actual_price');
|
|
|
|
$productInCart = $cart->products()->find($cartData->productId);
|
|
|
|
if ($productInCart) {
|
|
$newQuantity = $productInCart->pivot->quantity + $cartData->quantity;
|
|
|
|
$cart->products()->updateExistingPivot($cartData->productId, [
|
|
'quantity' => $newQuantity,
|
|
'price' => $price,
|
|
]);
|
|
|
|
} else {
|
|
$cart->products()->attach($cartData->productId, [
|
|
'quantity' => $cartData->quantity,
|
|
'price' => $price,
|
|
]);
|
|
}
|
|
|
|
return CartDTO::fromModel($cart->load(['products' => function ($query) {
|
|
$query->withPivot('quantity', 'price');
|
|
}]));
|
|
|
|
}
|
|
}
|