/** * Creates all recipe ingredients * * @param Request $request * @param int|string $recipeId */ private function saveIngredients(Request $request, $recipeId) { foreach ($request->get('ingredient') as $ingredient) { if (!$request->exists('amount-' . $ingredient)) { continue; } // creates new recipe ingredients if (is_numeric($ingredient)) { if (Ingredient::exists($ingredient) === false) { continue; } if ($request->exists('updateIngredient')) { DB::enableQueryLog(); if (in_array($ingredient, $request->get('updateIngredient'))) { $recipeIngredient = RecipeIngredient::where(function ($query) use($recipeId, $ingredient) { $query->where('recipe_id', '=', $recipeId)->where('ingredient_id', '=', $ingredient); })->first(); $recipeIngredient->amount = $request->get('amount-' . $ingredient); $recipeIngredient->save(); continue; } } $recipeIngredient = new RecipeIngredient(); $recipeIngredient->recipe_id = $recipeId; $recipeIngredient->ingredient_id = $ingredient; $recipeIngredient->amount = $request->get('amount-' . $ingredient); $recipeIngredient->save(); } else { $newIngredient = new Ingredient(); $newIngredient->name = ucfirst(str_replace('-', ' ', $ingredient)); if ($newIngredient->save()) { $recipeIngredient = new RecipeIngredient(); $recipeIngredient->recipe_id = $recipeId; $recipeIngredient->ingredient_id = $newIngredient->id; $recipeIngredient->amount = $request->get('amount-' . $ingredient); $recipeIngredient->save(); } } } }