Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kazehaya's avatar

sync question

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:

  • project_id
  • option_id
  • name

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".

0 likes
4 replies
JarekTkaczyk's avatar

@kazehaya Do you want to store files as additional data on the pivot table? If so, then use this:

 [
     5 => ["data" => "files"],
     4 => ["data" => "pictures"],
     3 => ["data" => "tags"],
     1 => ["data" => "thumbs"]
 ]

If not, then simply:

$project->options()->sync(array_keys($data));
kazehaya's avatar

@JarekTkaczyk

Im trying to get what you suggested but dont know how to achieve it:

here is how im building 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']);
JarekTkaczyk's avatar
Level 53

@kazehaya Given the array from your original question, you can build the one you need, like this:

$syncArray = array_build($data, function ($key, $value) {
    return [$key, ['data' => $value]];
});

//  [
//     5 => ["data" => "files"],
//     4 => ["data" => "pictures"],
//     3 => ["data" => "tags"],
//     1 => ["data" => "thumbs"]
// ]
2 likes

Please or to participate in this conversation.