Laravel笔记-搭建Restful风格的后端
短信预约 -IT技能 免费直播动态提醒
首先创建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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341