2017-07-28 114 views
0

我有一個Laravel Lumen API。我看到更新功能的問題。Lumen:通過json主體更新記錄

在我的控制器,用於更新項目的代碼是:

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的身體工作,所以不明白爲什麼它d oes不適用於更新。對於信息, '添加項目' 控制代碼是在這裏:

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

而不是這樣做:

$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改成數組,並用它來驗證和保存數據。

0

如果你想從請求負載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']);  
}