0

I have a form that has a dropdown where the user can select up to 5 countries.

I have two related tables, users and countries, where each user can have multiple countries selected.

The users table:

+----+----------+----------------------+
| id | username |     description      |
+----+----------+----------------------+
|  1 | user1    | Some description.    |
|  2 | user2    | Another description. |
+----+----------+----------------------+

The countries table:

+----+---------+---------------+
| id | user_id |    country    |
+----+---------+---------------+
|  1 |       1 | Canada        |
|  2 |       1 | United States |
|  3 |       1 | France        |
|  4 |       2 | Spain         |
|  4 |       2 | Italy         |
+----+---------+---------------+

As you can see, the country dropdown values should each have their own row in the table.

Here is my UserController so far (it only inserts into the users table for now):

$user = new User;
$user->username = Input::get('username');
$user->description = Input::get('description');
$user->save();

How would I insert multiple dropdown values such that each has its own row? What should my models look like for this to work?

  • 1
    I think you should have 3 tables here, users (list of users), countries (list of countries) and a user_country (the mapping between users and countries) – Dhiraj Mar 13 '15 at 20:22
  • That's not something I require in the design. It's still besides the point though and doesn't solve my issue. –  Mar 13 '15 at 20:24
  • Reading the [Laravel Eloquent Relationships Documentation](http://laravel.com/docs/5.0/eloquent#relationships) should point you in the right direction. – Bogdan Mar 13 '15 at 20:25
  • From the description in your question you have a **one-to-many** relationship, and for that you **do** need a pivot table for mapping relations like @Dhiraj Bodicherla pointed out. – Bogdan Mar 13 '15 at 20:27
  • possible duplicate of [Bulk Insertion in Laravel using eloquent ORM](http://stackoverflow.com/questions/12702812/bulk-insertion-in-laravel-using-eloquent-orm) – Limon Monte Mar 13 '15 at 21:19

1 Answers1

0

If you're gonna use eloquent to do it, here's a suggestion:

//in your User model

public function countries()
{
     return $this->hasMany('Country');
}

//insert from the controller

$countries = json_decode(Input::get('countries'), true); //assuming you use json to submit the multiple countries

$user_countries = array();
foreach($countries as $country)
{
    $user_countries[]=new Country(array('country'=>$country));
}

//save the countries into the DB
$user->countries()->saveMany($user_countries);

for more info, do refer to the documentation: http://laravel.com/docs/4.2/eloquent#inserting-related-models

har2vey
  • 676
  • 6
  • 19