返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >Laravel笔记-搭建Restful风格的后端
  • 647
分享到

Laravel笔记-搭建Restful风格的后端

laravelrestfulphp 2023-09-27 22:09:52 647人浏览 安东尼
摘要

首先创建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

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作