$countries = Country::all();
When a country is selected
$cities = City::where('country_id', $countryId)->get();
And when city is selected
$villages = Village::where('country_id', $countryId)
->where('city_id', $cityId)->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have 3 tables like these:
Countries Id | name 1 | country 2 | country
Citys Id | id_country | name 1 | 1 | city 2 | 2 | city2 3 | 1 | city3
Villages Id | id_country | id_city | name 1 | 1 | 2 | helloworld ...
I want make on select2 a searching and get country -> city -> village ( with children)
I'm out of ideas how I can do this in eloquent in laravel..
Help me please
@umbus consider the following route which provides the data, structured as select2 requires and i assume you have setup your relationships properly.
Route::get('/villages', function () {
return collect(['results'=>App\Models\Country::get()->map(function($country){
return collect(
[
'text' => $country->name,
'children' =>
$country->cities->map(function($city){
return collect([
'id' => $city->id,
'text' => $city->name,
'children' => $city->villages->map(function($village){
return collect([
'id' => $village->id,
'text' => $village->name
]);
})
]);
})
]
);
}),'pagination' => ['more' => false]])->toJson();
});
and in your view somewhere you have initialized a select as following example:
<select class="umbus-hierarchy"></select>
$('.umbus-hierarchy').select2({
ajax: {
url: '/villages',
dataType: 'json'
},
width: '100%',
placeholder: '- Select -'
});
the above example will work as you wanted. but according to the select2 library https://select2.org/options#hierarchical-options nesting more than 2 level is not supported. suppose if a city doesn't have a village you won't be able to select that city and same goes for country with a city and no village. because only the village is selectable...
~cheers
Please or to participate in this conversation.