Question :
I made a filter in laravel and it works perfectly but nevertheless it brings all the cities. It does not bring the specific cities of that state. I do not know if this filter has to go there in the laravel controller, how does it work for jquery? I’m using a Rest-Full web-service
I’m passing in the postman as follows:
link
LookatmytablesandmycontrollersinLARAVEL.IstillputJQUERY:
CONTROLLERmunicipalities
namespaceAppHttpControllers;useIlluminateHttpRequest;useAppMunicipios;classMunicipiosControllerextendsController{publicfunctionindex(){$municipios=Municipios::with('estados')->get();returnresponse()->json($municipios);}publicfunctionshow($id){print_r('teste');$municipios=Municipios::with('estados')->find($id);if(!$municipios){returnresponse()->json(['message'=>'Nãoháresultados',],404);}returnresponse()->json($municipios);}}
MODELMUNICIPALITIES
namespaceApp;useIlluminateDatabaseEloquentModel;classMunicipiosextendsModel{protected$fillable=['nome','cep'];protected$primaryKey='municipios_id';publicfunctionestados(){return$this->belongsTo('AppEstados');}}
MODELSTATES
namespaceApp;useIlluminateDatabaseEloquentModel;classEstadosextendsModel{protected$fillable=['nome','sigla'];protected$primaryKey='estados_id';publicfunctionmunicipios(){return$this->hasMany('AppMunicipios');}}
CONTROLLERSTATES:
namespaceAppHttpControllers;useIlluminateHttpRequest;useAppEstados;classEstadosControllerextendsController{//publicfunctionindex(){$estados=Estados::all();returnresponse()->json($estados);}}
ROUTESFILE:
useIlluminateHttpRequest;Route::get('/',function(){returnresponse()->json(['message'=>'RepApi','status'=>'Connected']);;});Route::resource('clientes','ClientesController');Route::resource('fornecedores','FornecedoresController');Route::resource('usuarios','UsuariosController');Route::resource('estados','EstadosController');Route::resource('municipios','MunicipiosController');Route::post('autenticacao','AuthController@authenticate');
MUNICIPALTABLES:
useIlluminateSupportFacadesSchema;useIlluminateDatabaseSchemaBlueprint;useIlluminateDatabaseMigrationsMigration;classCreateTableMunicipiosTableextendsMigration{/***Runthemigrations.**@returnvoid*/publicfunctionup(){Schema::dropIfExists('municipios');Schema::create('municipios',function(Blueprint$table){$table->increments('municipios_id');$table->integer('estados_id')->unsigned();$table->string('nome',100);$table->char('cep',10);$table->timestamps();$table->softDeletes();});}/***Reversethemigrations.**@returnvoid*/publicfunctiondown(){Schema::dropIfExists('municipios');}}
TABLESTATES:
useIlluminateSupportFacadesSchema;useIlluminateDatabaseSchemaBlueprint;useIlluminateDatabaseMigrationsMigration;classCreateTableEstadosTableextendsMigration{/***Runthemigrations.**@returnvoid*/publicfunctionup(){Schema::dropIfExists('estados');Schema::create('estados',function(Blueprint$table){$table->increments('estados_id');$table->string('nome',100);$table->char('sigla',2);$table->timestamps();$table->softDeletes();});}/***Reversethemigrations.**@returnvoid*/publicfunctiondown(){Schema::dropIfExists('estados');}}
JQUERY:
//outrasfunçõesdevalidaçãodoformuláriofunctionretorna_estados(){varopcaoCadastro="";
$.ajax({
url: url_base + "estados",
type: 'GET',
dataType: 'json',
success: function(data)
{
data.forEach(function (item)
{
opcaoCadastro = $("<option value=" + item.estados_id + " data-nome-estado='" + item.nome + "'>" + item.nome + "</option>");
$("#estado_cliente").append(opcaoCadastro);
opcaoCadastro = $("<option value=" + item.estado_id + " data-nome-estado='" + item.nome + "'>" + item.nome + "</option>");
$("#estado_fornecedor").append(opcaoCadastro);
});
},
error:function(data)
{
console.log(data);
}
});
}
// AO SELECIONAR UM ESTADO DA FEDERAÇÃO
$("#estado_cliente").change(function ()
{
var options_cidades = '';
var idEstado = "";
$("#estado_cliente option:selected").each(function ()
{
idEstado += $(this).attr('value');
$.ajax({
url: url_base + "municipios?filter[estados_id]=" + idEstado,
type: 'GET',
}).done(function (retorno)
{
$.each(retorno.data, function (key, val)
{
if (val.estados_id == idEstado)
{
options_cidades += '<option value="' + val.municipios_id + '" data-nome-cidade="' + val.nome +'">' + val.nome + '</option>';
$("#cidade_cliente").append(options_cidades);
}
});
}).fail(function (data)
{
console.log(data);
});
});
}).change();
Answer :
I do not do it in Laravel 5.2
View
<script type="text/javascript">
$('select[name=uf]').change(function () {
var uf = $(this).val();
$.get('/logistica/get-cidades/' + uf, function (busca) {
$('select[id=comarca_id]').empty();
$('select[id=comarca_id]').append('<option value=""> </option>');
$.each(busca, function (key, value) {
$('select[id=comarca_id]').append('<option value="' + value.id + '">' + value.name + '</option>');
});
});
});
Route
Route::get('/get-cidades/{uf}', [
'middleware' => 'auth',
'uses' => 'ExecucaoController@get_cidades'
]);
Note: remember that on the route I use a “logistical” prefix.
Controller
public function get_cidades($id)
{
$comarca = DB::table('cidades')
->where('uf','=', $id)
->orderBy('name','asc')
->get();
return Response::json($comarca);
}