我尝试在Laravel 5.6中构建RESTful API,现在我也想使用PUT和DELETE请求删除和更新数据库条目。如果我使用此代码,我不会出错,但总是收到“更新”或“已删除”的消息,但数据库永远不会更改。
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Car $car
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $number)
{
$bus = Bus::findOrFail($number);
$bus->update($request->all());
return response()->json(["message" => "Updated"]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Car $car
* @return \Illuminate\Http\Response
*/
public function destroy($number)
{
Bus::find($number)->delete();
return response()->json(["message" => "Deleted"]);
}
}
routes / api.php
Route::get('bus', 'BusController@index');
Route::post('bus', 'BusController@store');
Route::put('bus/{number}', 'BusController@update');
Route::delete('bus/{number}', 'BusController@delete');
答案 0 :(得分:0)
LARAVEL BLADE
如果您使用Laravel刀片,只需在表单开头添加method_field
csrf_field
(PUT / DELETE),如下所示:
<form action="bus/<your_id_or_number>" method="post" enctype="multipart/form-data">
{{ method_field('PUT') }}
{{ csrf_field() }}
... rest of your code ...
</form>
POSTMAN API
1。。如果您要在邮递员上测试API,请将API方法更改为 POST ,并使用key = _method添加新字段/参数和value = PUT ,如下图所示:
2。或在正文部分使用x-www-form-urlencoded
,方法类型为默认 PUT / DELETE ,例如: