Untitled
hoaily19
plain_text
5 months ago
2.5 kB
3
Indexable
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; use App\Models\Product; class ProductController extends Controller { /** * Display a listing of the resource. */ public function index(): JsonResponse { $products = Product::all(); return response()->json($products); } /** * Store a newly created resource in storage. */ public function store(Request $request): JsonResponse { $validated = $request->validate([ 'name' => 'required|string|max:255', 'description' => 'nullable|string|max:500', 'price' => 'required|numeric', 'image' => 'nullable|string|max:255', ]); $product = Product::create($validated); return response()->json([ 'message' => 'Create successfully', 'data' => $product ], 201); } /** * Display the specified resource. */ public function show(string $id): JsonResponse { $product = Product::find($id); if (!$product) { return response()->json(['message' => 'Product not found'], 404); } return response()->json($product); } /** * Update the specified resource in storage. */ public function update(Request $request, string $id): JsonResponse { $product = Product::find($id); if (!$product) { return response()->json(['message' => 'Product not found'], 404); } $validated = $request->validate([ 'name' => 'sometimes|string|max:255', 'description' => 'nullable|string|max:500', 'price' => 'sometimes|numeric', 'image' => 'nullable|string|max:255', ]); $product->update($validated); return response()->json([ 'message' => 'Update successfully', 'data' => $product ]); } /** * Remove the specified resource from storage. */ public function destroy(string $id): JsonResponse { $product = Product::find($id); if (!$product) { return response()->json(['message' => 'Product not found'], 404); } $product->delete(); return response()->json(['message' => 'Delete successfully']); } }
Editor is loading...
Leave a Comment