Try dumping your request on your regions route. It looks like it is expecting a "country" input but your script isn't passing it. This means your query is executing and trying to find any values with an empty country id, finds none, and so it returns an empty array
Aug 9, 2018
4
Level 2
Making dynamic dropdown with VueJS
I am making a dynamic dropdown list with VueJS , It fetch the countries but for the regions it give me empty array with no error, I couldn't find where is my mistake
My routes :
Route::get('/countries', 'HomeController@countries');
Route::get('/regions', 'HomeController@regions');
My controller:
class HomeController extends Controller
{
public function countries()
{
$countries = Country::all();
return response()->json(["countries" => $countries ]);
}
public function regions(Request $request)
{
$countriesId = $request->input('country');
$regions = Region::where('country_id', '=', $countriesId)->get();
return response()->json(["regions" => $regions ]);
}
}
my view:
<div id="app">
<form action="">
<div class="form-group">
<label for="country"></label>
<select v-model="country" name="country" class="form-control" @change="loadRegions">
<option>Select country</option>
<option v-for="country in countries" :value="country.id">@{{ country.name }}</option>
</select>
</div>
<div class="form-group">
<label for="region"></label>
<select v-model="region" name="region" class="form-control">
<option v-for="region in regions" :value="region.id">@{{ region.name }}</option>
</select>
</div>
</form>
</div>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/vue-select@latest"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data() {
return {
countries: [],
regions: [],
country: '',
region: '',
}
},
mounted() {
this.loadCountries()
},
methods: {
loadCountries() {
axios.get('/countries').then(response => this.countries =response.data.countries).catch(error => console.log(error))
},
loadRegions() {
axios.get('/regions').then(response => this.regions = response.data.regions).catch(error => console.log(error))
}
}
})
</script>
Level 104
You are not sending the selected country whenever you are trying to fetch the regions.
loadRegions() {
axios.get('/regions', {params: {country: this.country}}) // appends query string ?country=123
.then(response => this.regions = response.data.regions)
.catch(error => console.log(error))
}
Please or to participate in this conversation.