1

Now I am developing a web application which enable to make a recipe by selecting multiple foods retrieved from mysql and inputting its amount. My user interface is like this;

Html

<form action="{{ URL::route('store') }}" method="post">
    Your recipe name: <input type="text" name="recipe_name">

      <!-- Generating multiple rows with jquery-->
      '<tr>
        <td>' + add_food + '<input name="food[]" hidden="true" value="'+ add_food +'"></td>
        <td><input name="amount[]" class="amount" type="number"/></td>
      </tr>'

    <input type="submit" value="Make a recipe!">
</form>

Models and relation

I have already set up two table called Dish and Food which has many-to-many relation and these tables are intermediated by pivot table called dish_food.

What I want to do

I want to create new recipe called 'Pizza' which consists from 80g of bread, 20g of cheese and 10g of sausage. So in my UI I select these three foods and input its amounts, then submit these data. Finally I want to insert dish_id, food_id, amount like this;

dish_id| food_id|  amount
-------|--------|--------
     1 |      1 |     80 
     1 |      2 |     20
     1 |      3 |     10

Controller I am struggling now

public function store()
{
    // Here comes some validation...

    // Getting data from UI.

        $name     = Input::get('name');
        $foods    = Input::get('foods');  // $foods is storing multiple data.
        $amounts = Input::get('amount'); // $amounts is storing multiple data.

    // Store recipe name into Dish table.
        $dish = Dish::create([
            'name'  => $name
        ]);

    // Here is my problem.
        $food_ids = Food::where('name', '=', $foods)->get(['id']);

        foreach($food_ids as $position => $food_id){

            $dish->foods()->attach($food_id, array_get($amounts, $position));

        return Redirect::route('create-recipe')
                ->with('global', 'You have made one recipe!');
}

Problem

With the code above, I could insert a new recipe name into Dish table like this;

dish_id|  name
-------|--------
     1 |  pizza

But I can't insert multiple data into my pivot table dish_food, and I can not get any error message! So I need YOUR help. HOW TO FIX MY CODE?

I already checked related question like this;

Laravel attach pivot to table with multiple values

Community
  • 1
  • 1
Hanimar
  • 91
  • 1
  • 1
  • 4

1 Answers1

0

Maybe you are getting just one id in this line

 $food_ids = Food::where('name', '=', $foods)->get(['id']);

Try to change it to

$food_ids = Food::whereIn('name', $foods)->get(['id']);
Alien
  • 1