laravel - PUT 和 POST 方法的 REST 标准是什么?
问题描述
我正在 Laravel 中实现 API,并得到评论说我的 POST 和 PUT 方法根据 REST 标准不准确。
我使用 POST 创建新资源,使用 PUT 更新现有资源。看不出问题。
端点:
Route::post('/cities', [
'uses' => 'CityController@store'
]);
Route::put('/cities/{id}', [
'uses' => 'CityController@update'
]);
PUT
和POST
方法:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required|min:3',
'latitude' => 'required|numeric',
'longitude' => 'required|numeric'
]);
// update model and only pass in the fillable fields
$this->cityRepository->update(
$request->only($this->cityRepository->getModel()->fillable), $id
);
return $this->cityRepository->show($id);
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3',
'latitude' => 'required|numeric',
'longitude' => 'required|numeric'
]);
$data = $this->cityRepository->create(
$request->only($this->cityRepository->getModel()->fillable));
if ($data) {
$message = self::SUCCESSFULLY_CREATED;
$code = self::HTTP_CODE_CREATED;
} else {
$message = self::UNSUCCESSFULLY_CREATED;
$code = 409;
}
return $this->sendResponse($message, $data, $code);
}
发送响应:
public function sendResponse($message, $result = [], $code = 200)
{
$response = [
'message' => $message,
];
if (!empty($result)) {
$response['data'] = $result;
}
return response()->json($response, $code);
}
显示方法:
public function show($id)
{
return $this->model->findOrFail($id);
}
解决方案
您可以从您的方法返回创建的对象,store
而不是SUCCESSFULLY_CREATED
. 除此之外,代码看起来不错。
看看https://laravel.com/docs/5.8/controllers#resource-controllers上的表格,它有一个相当有用的各种 CRUD 路由的 REST 定义:
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy
这是您应该返回的 HTTP 方法的一个很好的资源:
推荐阅读
- java - 无法填充 ListView 未调用 getView
- python - 用空格替换名称之间的制表符
- ios - Spritekit 和 swift - 如何在测试期间从测试人员那里取回数据
- mongoose - 是否可以自定义猫鼬中的错误?
- javascript - js直播搜索模式
- java - 如何使用 Mybatis 和 PostgreSQL 创建一个空数组?
- c++ - 通过 Boost Python 在 C++ 对象之间传递共享指针的 Segfault
- java - 为什么我们在 Hibernate 配置或映射文件中写入标签
- javascript - DarkSky API - 未处理的拒绝错误 - ReactJS / Axios / Node.js
- scala - 如何从 Spark 数据框中的数组中获取统计信息?