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
country->name
becomes label of<optgroup>
city
is grouped by theircountry
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~