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.

8
  • possible duplicate of Bulk Insertion in Laravel using eloquent ORM Commented Mar 13, 2015 at 21:18
  • The answers there are from 2012. Laravel has changed a lot since then. Commented Mar 13, 2015 at 21:22
  • Also, insert() does not update created_at or updated_at. Commented Mar 13, 2015 at 21:26
  • Have you tried looping first to create the array itself and then inserting the array after the loop has finished? Commented Mar 13, 2015 at 21:29
  • Input::get('tags') already is an array. Not sure what you mean. Commented Mar 13, 2015 at 21:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.