首先创建Controller和resource
php artisan make:controller ProductsController -rphp artisan make:resource ProductResource
将ProductsController.php改为:
input('name'); $productPrice = $request->input('price'); $productDescription = $request->input('description'); $product = Products::create([ 'name' => $productName, 'price' => $productPrice, 'description' => $productDescription, ]); return response()->json([ 'data' => new ProductResource($product) ], 201); } public function show(Products $product) { return new ProductResource($product); } public function edit($id) { // } public function update(Request $request, Products $product) { $productName = $request->input('name'); $productPrice = $request->input('price'); $productDescription = $request->input('description'); $product->update([ 'name' => $productName, 'price' => $productPrice, 'description' => $productDescription ]); return response()->json([ 'data' => new ProductResource($product) ], 200); } public function destroy(Products &$product) { $product->delete(); return response()->json(null, 204); }}
PrductResource.php
$this->id, 'productName' => $this->name, 'discountedPrice' => "$" . ($this->price * 0.8), 'discount' => "$" . ($this->price * 0.2), 'productDescription' => $this->description, ]; }}
这里需要在routes/api.php中添加代码,不用在web.php中添加
get('/user', function (Request $request) { return $request->user();});Route::get('products', [ProductsController::class, 'index'])->name('products.index');Route::get('products/{product}', [ProductsController::class, 'show'])->name('products.show');Route::post('products', [ProductsController::class, 'store'])->name('products.store');Route::put('products/{product}', [ProductsController::class, 'update'])->name('products.update');Route::delete('products/{product}', [ProductsController::class, 'destroy'])->name('products.destroy');
运行截图如下:
来源地址:https://blog.csdn.net/qq78442761/article/details/129002888