Skip to content

Instantly share code, notes, and snippets.

@sabid
Last active March 29, 2023 00:55
Show Gist options
  • Save sabid/82192640d5365bb51f1a to your computer and use it in GitHub Desktop.
Save sabid/82192640d5365bb51f1a to your computer and use it in GitHub Desktop.
Laravel + Jquery Ajax Country and City
CREATE TABLE `paises` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
CREATE TABLE `ciudades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pais_id` int(11) DEFAULT NULL,
`nombre` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
Script
------------------------------
<script type="text/javascript">
$('select#country').change(function(){
var countryId = $(this).val();
$ciudaditems = $('.cityItems').remove();
$.get('/ciudades/'+countryId, function(data){
$.each(data, function(index, element){
//console.log(element);
$('select#city').append('<option value="'+element.id+'" class="cityItems">'+element.nombre+'</option>')
});
}, 'json');
});
});
</script>
View
------------------------------
Country :
<select name="country" class="country" id="country">
<option selected="selected">--Seleccionar Pais--</option>
@foreach($paises as $pais)
<option value="{{ $pais->id }}">{{ $pais->nombre }}</option>
@endforeach
</select> <br/><br/>
Ciudad :
<select name="city" class="city" id="city">
<option selected="selected">--Seleccionar Ciudad--</option>
</select>
Route
--------------------------
Route::get('/ciudades/{id}', function($id)
{
$pais_id = $id;
$ciudades = Pais::find($pais_id)->ciudades;
return Response::json($ciudades);
});
Model Pais
------------------------
class Pais extends \Eloquent {
protected $table = 'paises';
public function ciudades()
{
return $this->hasMany('ciudad');
}
}
Model Ciudad
-----------------------
class Ciudad extends \Eloquent {
protected $table = 'ciudades';
public function pais()
{
return $this->belongsTo('pais');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment