Laravel, Sync() - How to Sync an Array and Also Pass Additional Pivot Fields

Laravel, sync() - how to sync an array and also pass additional pivot fields?

There is now a ->syncWithPivotValues($ids, $pivotValues) method available if you want to set the same pivot value for all synced items.

Example from the doc:

$user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]);

Laravel, sync data with Pivot

->sync() isn't used like that; it's used to attach() and detach() related new_function_ids until only the ids in sync() are present. You're probably looking for updateExistingPivot()

An example of ->sync() would be using the array:

$user->newFunctions()->sync([
"new_function_id" => 1,
"function_count" => 6,
"days_count" => "2019-07-08 12:00:00",
]);

This would remove the record where new_function_id is 3, and updating the values where new_function_id is 1.

To update function_count and days_count for either new_function_id of 1 or 3, use ->updateExistingPivot() (pass the id you want to update as the first parameter):

$user
->newFunctions()
->updateExistingPivot("1", [
"function_count" => 6,
"days_count" = "2019-07-08 12:00:00"
]);
// or $user->newFunctions()->updateExistingPivot("3", ...);

This will update the pivot table where new_function_id is 1, while leaving the row where new_function_id is 3.

Edit: If you're looking to update all existing records in the pivot table, you'll need to do this in a loop, call a sync with all current records in a single array, or run a manual query.

Laravel 5: syncing an extra field via pivot

You are actually pretty close. The required format is:

[
98 => ['company_id' => 129],
99 => ['company_id' => 130],
100 => ['company_id' => 131]
]

This should generate the correct array:

$extra = array_map(function($companyId){
return ['company_id' => $companyId];
}, $allCompanyIds);

$data = array_combine($allPositionIds, $extra);

$user->positions()->sync($data);

How to pass pivot table additional columns values using the sync method

The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:

$item->species()->sync([1, 2, 3]);

You may also pass additional intermediate table values with the IDs:

$item->species()->sync([1 => ['number' => 4, 'weight' => 20]);

Note that you have to use a nested array. Where the key of the array is the id of the element to associate and its content the extra columns of your pivot table.

$attach = collect($data['species'])->mapWithKeys(function ($specie) {
return [$specie => ['number' => 4, 'weight' => 20]];
});

$item->species()->sync($attach);

Laravel: extra field sync with array

This is covered in the manual:

Adding Pivot Data When Syncing

You may also associate other pivot table values with the given IDs:

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

In your example, you would have to change your array to look something like below but I believe this would translate to:

$data = [
5 => [ 'name' => "files" ],
4 => [ 'name' => "pictures" ],
3 => [ 'name' => "tags" ],
1 => [ 'name' => "thumbs" ],
];

$project->options()->sync($data);

I believe you may also need to modify how your Project model relates itself to your Options model:

// File: app/model/Project.php
public function options()
{
return $this->belongsToMany('Option')->withPivot('name');
}

This is also noted in the linked-to manual page:

By default, only the keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship.

Update

Try creating your $data array like this:

$data = [];
foreach($request->input('option_id') as $id) {
$data[$id] = [ 'name' => $request->input('data')[$id] ];
}

sync an array with pivot attributes in Laravel

Well I did something like this:

foreach ($data['clientParticipants'] as $clientParticipant)
{
if(array_key_exists('company_id', $clientParticipant))
{
$pivotData = ['company_id' => $clientParticipant['company_id']];
$syncData = Contact::find(json_encode($clientParticipant['value']))->id;
$contact[$syncData] = $pivotData;
}
else
{
$value = Contact::find(json_encode($clientParticipant['value']));
$syncData = $value->id;
$pivotData = ['company_id' => $value->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first()->id];
$contact[$syncData] = $pivotData;
}
}
$interaction->clientsAssociation()->sync($contact);

And it works. So basically idea is to push an array with key of pivot elements and it will execute properly.

Laravel Many to Many Sync with additional column

While attach you can pass an additional array as you have passed.

$item->users()->attach($request->clients, ['role'=>'client']);
$item->users()->attach($request->employees, ['role'=>'employee']);

But In the sync you have to pass pivot value inside the array, I have mention example below.

$item->roles()->sync([1 => ['role' => 'client'], 2 => ['role' => 'employee']);

Check documentation sync part,



Related Topics



Leave a reply



Submit