Home >Backend Development >PHP Tutorial >How to Sync ModelRelationships with Additional Pivot Fields in Laravel?
Laravel: Sync() with Additional Pivot Fields
In Laravel, the sync() function is used to synchronize a model relationship with a set of IDs. However, it is also possible to specify additional pivot fields when syncing.
Default Usage:
As described in the Laravel documentation, you can sync a simple set of IDs like this:
<code class="php">$user->roles()->sync([1, 2, 3]);</code>
Syncing with Pivot Fields:
If you want to associate specific pivot table values with the IDs, you can specify them as an array:
<code class="php">$user->roles()->sync([ 1 => ['expires' => true] ]);</code>
This example adds a single pivot row with the expires field set to true.
Multiple Pivot Records with Custom Data:
To sync multiple models with custom pivot data, you can use the following syntax:
<code class="php">$user->roles()->sync([ 1 => ['expires' => true], 2 => ['expires' => false], ... ]);</code>
This example syncs two roles, each with its own expires value.
Example with Array Input:
If you are receiving IDs and pivot data as an array, you can use array_combine() to create the sync data:
<code class="php">$speakers = (array) Input::get('speakers'); // Get related IDs $pivotData = array_fill(0, count($speakers), ['is_speaker' => true]); $syncData = array_combine($speakers, $pivotData); $user->roles()->sync($syncData);</code>
By following these guidelines, you can effectively sync data with custom pivot fields in Laravel.
The above is the detailed content of How to Sync ModelRelationships with Additional Pivot Fields in Laravel?. For more information, please follow other related articles on the PHP Chinese website!