Laravel attach pivot to table with multiple values

Duncan Ogle picture Duncan Ogle · Apr 22, 2014 · Viewed 57.8k times · Source

Background

I'm creating a database revolving around food allergies and I have a many to many relationship between foods and allergies. There is also a pivot value called severity which has a numerical number representing the severity of the allergy for that food item.

This link table looks like this;

food_id|allergy_id|severity
-------|----------|--------
     1 |        1 |      3
     1 |        4 |      1
     2 |        2 |      1

The problem

When trying to update the link table with Eloquent (where $allergy_ids is an array)

$food->allergies()->attach($allergy_ids);

How would I go about adding multiple values to this pivot table at once along with the pivot values?

I can add all the allergy_id's for a particular food item in one go using the above line, but how can I also add in the severity column at the same time with an array of various severity values? Maybe something like

$food->allergies()->attach($allergy_ids, $severity_ids);

Edit: There could be between 0-20 allergies for a specific food item, and a severity rating from 0-4 for each allergy, if this helps at all.

Answer

Nuno Rafael Figueiredo picture Nuno Rafael Figueiredo · May 20, 2015

You can.

From this example in Docs (4.2, 5.0):

$user->roles()->sync(array(1 => array('expires' => true)));

Hardcoded version for the first two rows:

$food = Food::find(1);
$food->allergies()->sync([1 => ['severity' => 3], 4 => ['severity' => 1]]);

Dynamically, with your arrays $allergy_ids and $severities in a compatible state (size and sort), you shall prepare your sync data before. Something like:

$sync_data = [];
for($i = 0; $i < count($allergy_ids); $i++))
    $sync_data[$allergy_ids[$i]] = ['severity' => $severities[$i]];

$food->allergies()->sync($sync_data);