// bad code
function getProduct(
int $id,
int $accessUserId,
bool $status,
array $filters,
bool $isTest
): Product
{
// do something...
return $product;
}
// good code
function getProduct(int $id): Product
{
// do something...
return $product;
}
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Enums\ProductType;
use Illuminate\Http\JsonResponse;
class ProductController extends Controller
{
public function show(int $id): JsonResponse
{
$product = Product
// 已啟用
::where('status', true)
// 主商品
->where('type', ProductType::MAIN)
->with([
'specs' => fn($query) => $query->where('status', true)
])
->findOrFail($id);
return response()->json([
// 商品資料
'id' => $product->id,
'name' => $product->name,
'created_at' => $product->created_at->toDateTimeString(),
'update_at' => $product->updated_at->toDateTimeString(),
// 規格資料
'specs' => $product->specs->map(fn($spec) => [
'id' => $spec->id,
'name' => $spec->name,
'price' => $spec->price,
'stocks' => max($spec->stocks, 15), // 最多限購 15 個
])
]);
}
}