/** * * @param $recipe * @param $steps */ public function insertRecipeMethod($recipe, $steps) { $step_number = 0; foreach ($steps as $step_text) { $step_number++; $method = new RecipeMethod(['step' => $step_number, 'text' => $step_text]); $method->user()->associate(Auth::user()); $method->recipe()->associate($recipe); $method->save(); } return $recipe; }
/** * UPDATE /api/recipes/{recipes} * @param Request $request * @param Recipe $recipe * @return Response */ public function update(Request $request, Recipe $recipe) { if ($request->get('removeIngredient')) { //This line didn't work so I'm using DB::table instead // $recipe->foods()->detach([$request->get('food_id') => ['unit_id' => $request->get('unit_id')]]); DB::table('food_recipe')->where('food_id', $request->get('food_id'))->where('unit_id', $request->get('unit_id'))->delete(); } else { if ($request->get('addIngredient')) { $recipe->foods()->attach($request->get('food_id'), ['unit_id' => $request->get('unit_id'), 'quantity' => $request->get('quantity'), 'description' => $request->get('description')]); } else { // Create an array with the new fields merged $data = array_compare($recipe->toArray(), $request->only(['name'])); $recipe->update($data); if ($request->has('tag_ids')) { $ids = $request->get('tag_ids'); $pivotData = array_fill(0, count($ids), ['taggable_type' => 'recipe']); $syncData = array_combine($ids, $pivotData); $recipe->tags()->sync($syncData); } if ($request->has('steps')) { //Remove the existing steps from the recipe $currentSteps = $recipe->steps()->delete(); //Attach the updated steps to the recipe $count = 0; foreach ($request->get('steps') as $step) { $count++; $step = new RecipeMethod(['step' => $count, 'text' => $step]); $step->user()->associate(Auth::user()); $step->recipe()->associate($recipe); $step->save(); } } if ($request->has('ingredients')) { //Remove the existing ingredients from the recipe $currentFoodIds = $recipe->foods()->lists('id')->all(); $recipe->foods()->detach($currentFoodIds); //Attach the updated ingredients to the recipe foreach ($request->get('ingredients') as $ingredient) { $recipe->foods()->attach([$ingredient['food_id'] => ['unit_id' => $ingredient['unit_id']]]); } } } } $recipe = $this->transform($this->createItem($recipe, new RecipeWithIngredientsTransformer()))['data']; return response($recipe, Response::HTTP_OK); }