Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ledah's avatar
Level 1

LaravelCollective create single Form Select from 2 tables combined

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~

0 likes
4 replies
jcmargentina's avatar

pseudo code in 3 ... 2 .... 1

  1. retrieve name, country_id and id of all city elements in a collection
  2. groupBy that collection by country_id
  3. transform that collection to an array 3.1) using a var_dump inspect the content of that array so you understand the structure of it
  4. send that array to your view
  5. process that array in your view using a foreach in order to build your html control

cheers!

ledah's avatar
Level 1

thanks @jcmargentina , but is there a way to still use LaravelCollective? also sorry if my question is vague. I've edited the post to clarify what kind of input I need for LaravelCollective.

jcmargentina's avatar

my friend, you can still get the array you want , only change "country_id" for "name" in step 2.

Check the Collection Section of the laravel documentation, everything you need is there + the pseudo code I gave you. Give it a look. Keep it up!!!!

ledah's avatar
Level 1

I re-read the documentation looking for things that I might've missed, didn't find a Laravel helper that can manipulate array exactly as I need.

So I asked my senior co-worker. And he said yeah there's none and I should manipulate array manually.

And here it is:

$countries= Country::all();
$cities = array();

foreach ($countries as $key => $country) {
    $cityName = array();
    foreach ($country->city as $key => $city) {
        $cityName[$city->id] = $city->name;
    }
    $cities[$country->name] = $cityName;
}

Please or to participate in this conversation.