我正在Laravel中实现API,并得到评论说,根据REST标准,我的POST和PUT方法不准确。
我正在使用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);
}
答案 0 :(得分:0)
您可以从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方法的好资源: