1

I have 2 tables, country and city:

table 'country'
+----+------------+
| id |    name    |
+----+------------+
|  1 | Indonesia  |
|  2 |  Malaysia  |
+----+------------+

country has many city, so country_id is the foreign key:

table 'city'
+----+------------+------------+
| id |      name  | country_id |
+----+------------+------------+
|  1 |   Jakarta  |          1 |
|  2 |  Surabaya  |          1 |
|  3 |   Kuching  |          2 |
+----+------------+------------+

I would like to use Laravel Collective to create a grouped drop-down list so that

  1. country->name becomes label of <optgroup>
  2. city is grouped by their country and becomes value of <option> in HTML <select>

What I need for LaravelCollective is to create array that looks like this:

[
    'Indonesia' => ['1' => 'Jakarta', '2' => 'Surabaya'],
    'Malaysia' => ['3' => 'Kuching']
]    

City::get(['name', 'country_id', 'id'])->toArray() gave me grouped array, but not key-value paired and country_id is still inside the created array.

Is there a good way to do this? Do I have to use foreach on either controller or view with traditional HTML <select> instead of Laravel Collective or 2 drop-down linked with JavaScript?

Thanks~

  • Well, you can use ajax call instead get all cities at the first. When user select a country, you can get only this cities –  Feb 27 '18 at 09:42
  • I'm aware of that. But what I would like to achieve is only using single drop-down for combined country & city, not one drop-down for each of them. – Hilman Faiz Feb 27 '18 at 11:21

0 Answers0