Question

is it possible to save more data than just the id's to a many-to-many pivot?

My Code:

    public function lists() {
        return $this->belongsToMany('ShoppingList','shopping_list_ingredients','shopping_list_id','ingredients_id')
        ->withPivot(array('unit','amount'))
        ->withTimestamps();
}  

and vice verca!
And now, I need to add the additional data to the pivot.

This is my saving code:

    $list = new ShoppingList;
    $list->user_id = Auth::user()->id;
    $list->title = Input::get('recipe_title');
    $list->save();
    $list->ingredients()->sync(Input::get('ingredient'));
    $list->push();  

and my view code:

- {{$i->amount}} {{$i->unit}} {{$i->name}} - {{ Form::checkbox('ingredient[]', $i->id) }}<br/>  

Now I need somehow pass the "amount" and "unit" for each ID into the controller and into the pivot. Right now, it only saves the IDs.

How can I do it?

Was it helpful?

Solution 2

You may try something like this:

$ingredientId = Input::get('ingredient');
$amount = 'some amount';
$unit = 'some unit';
$pivotData = array($ingredientId => array('amount' => $amount, 'unit' => $unit));

$list->ingredients()->sync($pivotData);

You may also use attach method, read the documentation on Laravel Website for more information.

OTHER TIPS

You have to use the attach function.

$list->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top