I have created a dependent dropdown menu for Laravel which connects Countries and States which works perfect for create.blade.php without an issue
Javascript used:
jQuery(document).ready(function ()
{
jQuery('select[name="country"]').on('change',function(){
var countryID = jQuery(this).val();
if(countryID)
{
jQuery.ajax({
type : "GET",
url : '<?php echo url('/'); ?>/admin/country/' + (countryID) + '/states/',
dataType : "json",
success:function(data)
{
console.log(data);
jQuery('select[name="state"]').empty();
$('select[name="state"]').append('<option value=""></option>');
jQuery.each(data, function(key,value){
$('select[name="state"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}
else
{
$('select[name="state"]').empty();
}
});
});
In Controller
public function getCountries()
{
$countries = DB::table('countries')->pluck("name","id");
return json_encode($countries);
}
public function getStates($id)
{
$states = DB::table("states")->where("countries_id",$id)->pluck("name","id");
return json_encode($states);
}
public function getDistricts($id)
{
$states = DB::table("districts")->where("states_id",$id)->pluck("name","id");
return json_encode($states);
}
public function getTowns($id)
{
$towns = DB::table("towns")->where("districts_id",$id)->pluck("name","id");
return json_encode($towns);
}
In edit.blade.php I'm using:
@foreach ($states as $state)
<option value="" ></option>
@endforeach
To retrieve the selected data from DB. Everything till now is perfect however in the Edit section it's populating everything in DB from Table States skipping dependencies of the country ID. For example it shows all states of the world instead of USA only since USA is the chosen country on creation. I'm stuck can't find a solution anyone can help please?
One other thing I've been thinking of, is change the connection of dependent dropdown from MySQL Database to be connected to a resources file for example resources > lang > en > countries.php and states.php aiming to optimize load of database queries for better performance. Any advice?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire