/** * Store a newly created resource in storage. * * @return Response */ public function store(FoodFormRequest $request) { $data = $request->all(); $user_id = Auth::user()->id; $food = new Food(); $food->name = $request->get('name'); if (isset($data['compound_food'])) { $food->brand_id = 23; //brand name 'Homemade' } else { $food->brand_id = $request->get('brand'); } $food->kcal = $request->get('kcal'); $food->proteins = $request->get('proteins'); $food->carbs = $request->get('carbs'); $food->fats = $request->get('fats'); $food->fibre = $request->get('fibre'); $food->user_id = $request->user()->id; $food->save(); if (isset($data['compound_food']) && $data['compound_food']) { $last_inserted_id = $food->id; $ingredientsInArray = array(); $arrayId = $data['ingredient']; $arrayWeight = $data['ingredient-weight']; for ($i = 0; $i < count($arrayId); $i++) { $ingredientsInArray[$i]["ingredient_id"] = $arrayId[$i]; $ingredientsInArray[$i]["ingredient_weight"] = $arrayWeight[$i]; } foreach ($ingredientsInArray as $smallArray) { $ingredient = new Ingredient(); $ingredient->food_id = $last_inserted_id; $ingredient->ingredient_id = $smallArray['ingredient_id']; $ingredient->weight = $smallArray["ingredient_weight"]; $ingredient->user_id = $user_id; $ingredient->save(); } } $message = "Food has been successfully added"; return redirect('food/index')->withMessage($message); }