/** * */ private function createRecipes() { foreach (Config::get('recipes') as $tempRecipe) { $recipe = new Recipe(['name' => $tempRecipe['name']]); $recipe->user()->associate($this->user); $recipe->save(); foreach ($tempRecipe['ingredients'] as $ingredient) { $food = Food::where('user_id', $this->user->id)->where('name', $ingredient['food'])->first(); $recipe->foods()->attach([$food->id => ['unit_id' => Unit::where('user_id', $this->user->id)->where('name', $ingredient['unit'])->first()->id, 'quantity' => $ingredient['quantity'], 'description' => $ingredient['description']]]); } foreach ($tempRecipe['tags'] as $tempTag) { $tag = Tag::where('user_id', $this->user->id)->where('name', $tempTag)->first(); $recipe->tags()->attach([$tag->id => ['taggable_type' => 'recipe']]); } $recipe->save(); } }
/** * 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); }