Im trying to save data inside a pivot table with an extra field called data.
when i save i have this array:
[
5 => "files"
4 => "pictures"
3 => "tags"
1 => "thumbs"
]
My table looks like this:
The ids shown above refer to option_id and the string to name inside the database.
When i try to use sync like this: $project->options()->sync($data);
$data is the array shown above
Im getting a error thats its trying to save the option_id with "files".
Here is how i build up the data that i use for sync:
Im trying to get what you suggested but dont know how to achieve it:
here is how i build up the array:
foreach($request->input('option_id') as $id) {
$option['option_id'][] = $id;
$option['data'][] = $request->input('data')[$id];
}
$data = array_combine($option['option_id'], $option['data']);
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] ];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With