Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: extra field sync with array

Tags:

php

laravel

sync

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']);
like image 806
kazehaya Avatar asked Dec 02 '22 14:12

kazehaya


1 Answers

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] ];
} 
like image 67
Jeff Lambert Avatar answered Dec 10 '22 17:12

Jeff Lambert