0

I have a multiple select:

Form::select('color', array('1' => 'Red', '2' => 'Blue', '3' => 'Green', ... ), null, array('multiple'));

How can I insert these values into a table on separate rows, like this:

  id  |  user_id  |  color
----------------------------
   1  |     1     |    1
   2  |     1     |    2
   3  |     1     |    3
   4  |     1     |    4
   5  |     2     |    1
   6  |     2     |    3

In the above example, user with an id of 1 selected 4 different values in the select and each was inserted on a separate row.

I have this working in this way:

foreach (Input::get('tags') as $key => $value)
{
    $user_color = new UserColor;
    $user_color->user_id = $user->id;
    $user_color->color = $key;
    $user_color->save();
}

Is there a better way of doing this? It seems odd using a foreach loop when it feels like Laravel should have some sort of built-in method of inserting multiple values on multiple rows.

1 Answers1

1

As Laravel doc provided,

You may also use the sync method to attach related models. The sync method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model:

In this case,

$colors = Input::get('tags');
$user->colors()->sync($colors);

Please make sure to set relation in your User model :

public function colors()
{
    return $this->belongsToMany('Color');
}

You can also use attach method when you parameter is not array. To more clear, Here is difference between attach and sync.

Community
  • 1
  • 1
Arkar Aung
  • 3,554
  • 1
  • 16
  • 25