Laravel attach pivot to table with multiple values Laravel attach pivot to table with multiple values laravel laravel

Laravel attach pivot to table with multiple values


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);


You can't do it like you' like so I suggest a simple loop:

foreach ($allergy_ids as $key => $id){  $food->allergies()->attach($id, array_get($severity_ids, $key));  // should you need a sensible default pass it as a 3rd parameter to the array_get()}

workaroundHowever if you wanted to attach multiple allergies with single severity level/id then you could do this:

$food->allergies()->attach($allergy_ids, array('severity' => $singleSeverityValue));


From version 5.1 of Laravel (Currently in Laravel 8.x) onwards it is possible to pass an array as a second argument with all the additional parameters that need to be saved in the intermediate table.As you can read in the documentation

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

$user->roles()->attach($roleId, ['expires' => $expires]);

For convenience, attach and detach also accept arrays of IDs as input:

$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);

Then you can simply do

$food->allergies()->attach([1 => ['severity' => 3], 4 => ['severity' => 1]]);