Exemplo n.º 1
0
 /**
  * UPDATE /api/foods/{foods}
  * @param Request $request
  * @param Food $food
  * @return Response
  */
 public function update(Request $request, Food $food)
 {
     if ($request->get('updatingCalories')) {
         //We are updating the calories for one of the food's units
         $food->units()->updateExistingPivot($request->get('unit_id'), ['calories' => $request->get('calories')]);
     } else {
         // Create an array with the new fields merged
         $data = array_compare($food->toArray(), $request->only(['name']));
         $food->update($data);
         if ($request->has('default_unit_id')) {
             $food->defaultUnit()->associate(Unit::findOrFail($request->get('default_unit_id')));
             $food->save();
         }
         if ($request->has('unit_ids')) {
             $food->units()->sync($request->get('unit_ids'));
         }
     }
     $food = $this->transform($this->createItem($food, new FoodTransformer()))['data'];
     return response($food, Response::HTTP_OK);
 }