php - Laravel: extra field sync with array

628

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

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']);
777

Answer

Solution:

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 yourProject model relates itself to yourOptions 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] ];
} 

People are also looking for solutions to the problem: php - Help with regexp

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.