fixed carts

This commit is contained in:
Edward Yang 2022-06-28 17:05:11 +08:00
parent 86c33778a6
commit dc4a11f43c
5 changed files with 40 additions and 7 deletions

View File

@ -112,7 +112,7 @@ function locale(): string
*/
function currency_format($price): string
{
return '$' . $price;
return '$' . number_format($price, 2);
}
/**

View File

@ -13,6 +13,6 @@ class Cart extends Model
public function sku()
{
return $this->belongsTo(ProductSku::class);
return $this->belongsTo(ProductSku::class, 'product_sku_id', 'id');
}
}

View File

@ -13,6 +13,7 @@ class CartController extends Controller
$data = [
'carts' => CartService::list(current_customer())
];
dump($data);
return view("cart", $data);
}

View File

@ -0,0 +1,33 @@
<?php
namespace Beike\Shop\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Resources\Json\JsonResource;
class CartList extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array|Arrayable|\JsonSerializable
*/
public function toArray($request)
{
$sku = $this->sku;
$price = $sku->price;
$subTotal = $price * $this->quantity;
return [
'product_id' => $this->product_id,
'sku_id' => $this->product_sku_id,
'image' => image_resize($sku->image),
'price' => $price,
'price_format' => currency_format($price),
'quantity' => $this->quantity,
'subtotal' => $subTotal,
'subtotal_format' => currency_format($subTotal),
];
}
}

View File

@ -11,19 +11,18 @@
namespace Beike\Shop\Services;
use Beike\Models\Cart;
use Beike\Models\Customer;
use Beike\Models\ProductSku;
use Beike\Shop\Http\Resources\CartList;
class CartService
{
public static function list($customer)
public static function list($customer): array
{
if (empty($customer)) {
return [];
}
$cartList = Cart::query()->where('customer_id', $customer->id)->get();
$cartItems = Cart::query()->where('customer_id', $customer->id)->get();
$cartList = CartList::collection($cartItems)->jsonSerialize();
return $cartList;
}