Home >Backend Development >PHP Tutorial >How to Assign Additional Pivot Table Values in Laravel when Syncing an Array?
The Laravel sync() method allows you to synchronize a model's relationship with an array of related IDs. But what if you need to associate additional pivot table values with these IDs?
The documentation example only shows how to assign pivot values for a single model. To assign values for multiple models, use the following syntax:
<code class="php">$user->roles()->sync([ 1 => ['expires' => true], 2 => ['expires' => false], ... ]);</code>
This syntax allows you to specify pivot values for each related model using the array key-value pairs.
Consider a scenario where you're handling form input to assign speakers to an event. The input is an array of speaker IDs and you need to set the is_speaker column in the pivot table to true.
Here's how you can achieve this:
<code class="php">$speakers = (array) Input::get('speakers'); // related ids $pivotData = array_fill(0, count($speakers), ['is_speaker' => true]); $syncData = array_combine($speakers, $pivotData); $user->roles()->sync($syncData);</code>
By using array_fill() and array_combine(), you can create an array of pivot values with the desired key-value pairs and then sync them with the model's relationship.
The above is the detailed content of How to Assign Additional Pivot Table Values in Laravel when Syncing an Array?. For more information, please follow other related articles on the PHP Chinese website!