我有一个Laravel Lumen API。我发现更新功能存在问题。
在我的控制器中,更新项目的代码是:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required',
]);
$todo = Todo::find($id);
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
我可以使用以下方式更新待办事项:
http://lumen-todo.app/api/51?name=test&description=test&completed=1
然而希望我可以在json体中发送参数,比如
PUT http://lumen-todo.app/api
{
"id": 1
"name": "Test",
"description": "Test",
"completed": 1,
}
对于添加项目,它通过json正文工作,所以不要理解为什么它不适用于更新。有关信息,请添加项目'控制器代码在这里:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
答案 0 :(得分:1)
如果要从请求有效负载中获取json数据,请验证并存储它,请使用
public function store(Request $request)
{
$data = $request->json()->all();
$this->validate($data, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
return response()->json(['status' => 'success']);
}
答案 1 :(得分:0)
而不是这样做:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
这样做:
use App\Todo;
protected $model;
public function __construct(Todo $model) {
$this->model = $model;
}
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
此外,您可以执行json_decode()
函数将json params更改为数组,并使用它来验证和保存数据。