首先创建Controller和resource PHP artisan make:controller ProductsController -rphp artisan make:resource ProductResource 将Prod
首先创建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
--结束END--
本文标题: Laravel笔记-搭建Restful风格的后端
本文链接: https://www.lsjlt.com/news/420143.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0