Ad

Laravel Insert Or Update Related Records

- 1 answer

I'm having trouble updating and creating related records depending on if they exist or not. I want to update the ingredient if they exist, if not insert the ingredient into the database and relate it to the current meal.

public function update($id)
{
    $meal = Meal::find($id);
    $meal->name = Input::get('name');

    // create ingredients
    $ingredients = Input::get('ingredient');
    $meal_ingredients = array();

    foreach($ingredients as $ingredient)
    { 
        $meal_ingredients[] = new Ingredient(array(
            'name' => $ingredient['name'],
            'unit' => $ingredient['unit'],
            'quantity' => $ingredient['quantity']
        ));
    }

    //save  into the DB
    $meal->save();
    $meal->ingredients()->saveMany($meal_ingredients);

    // redirect
    Flash::success('Votre repas a bien été mis à jour!');
    return Redirect::to('/meals');
}
Ad

Answer

Step 1 : Get Meal

 $meal = Meal::find($id);

Step 2 : Get Ingredients of Meal (create relation for this)

 $ingredients = $meal->ingredients;

Step 3 : Compare Input to current and add does not exist

$new_ingredients = array();

foreach($ingredients as $ingredient)
{ 
    if(!in_array($ingredient->toArray(), Input::get('ingredient')) {
      $new_ingredients[] = new Ingredient(array(
        'name' => $ingredient['name'],
        'unit' => $ingredient['unit'],
        'quantity' => $ingredient['quantity']
      ));
    }
}

Step 4 Update

$meal->ingredients->saveMany($new_ingredients);

Ensure you got the relation between meal and ingredient correctly

Ad
source: stackoverflow.com
Ad