Combo Cities with Laravel 5.2

Asked

Viewed 851 times

3

I’m starting my studies on Laravel. My project is a simple customer registration where I would like to do a combo of States with Cities.

Follow codes:

MODEL STATES

<?php

namespace SGW;

use Illuminate\Database\Eloquent\Model;

class Estado extends Model
{

    public $timestamps = false;
    protected $table = 'estados';
    protected $guarded = ['id'];

     protected $fillable = array(
        'nome', 
        'sigla', 
    );

    public function cidades()
    {
        return $this->hasMany('SGW\Cidade');
    }
}

MODEL CITIES

<?php

namespace SGW;

use Illuminate\Database\Eloquent\Model;

class Cidade extends Model {

    public $timestamps = false;
    protected $table = 'cidades';
    protected $guarded = ['id'];

    protected $fillable = array(
        'cidade', 
        'estado_id', 
    );

    public function estado()
    {
        return $this->belongsTo('SGW\Estado');
    }
}

CONTROLLER CITIES

<?php

namespace SGW\Http\Controllers;

use Illuminate\Support\Facades\DB;
use SGW\Cidade;
use Illuminate\Support\Facades\Request;
use Session;
use SGW\Estado;

class CidadesController extends Controller
{

    private $estadoModel;
    public function __construct(Estado $estado)
    {
        $this->estadoModel = $estado;
    }

    public function getCidades()
    {
        $estado = $this->estadoModel->findOrFail(13);
        $cidades = $estado->cidades()->getQuery()->get(['id', 'cidade']);
        return Response::json($cidades);
    }

    public function estado()
    {
       return $this->belongsTo('SGW\Estado', 'estado_id')
    }
}

ROUTES

Route::get('/', function () { return view('layout.index'); });
Route::resource('empresa', 'EmpresasController');
Route::get('/empresa/get-cidades', 'CidadesController@getCidades');

HTML CADASTRO

<div class="form-group">
      <div class="col-xs-11">
           <label for="estado">*Estado</label>
           <select class="form-control" id="estado"  name="estado" required>
               <option value=""></option> 
                @foreach ($estados as $e)
                    <option value="{{$e->id}}">[ {{$e->sigla}} ]  - {{$e->nome}}</option> 
               	@endforeach
            </select>
        </div>  
 </div>    


 <div class="form-group">
      <div class="col-xs-11">
          <label for="cidade">*Cidade</label>
          <select class="form-control" id="cidade" name="cidade"></select>
      </div>  
</div>

@section('post-script')
<script type="text/javascript">
    
    $('select[name=estado]').change(function () {
            
        var idEstado = $(this).val();

        $.get("{{ action ('CidadesController@getCidades') }} ", function (cidades) {

        	$('select[name=cidade]').empty();
        	$('select[name=cidade]').append("<option value='' disabled selected style='display:none;'>Selecione uma cidade</option>");

        	$.each(cidades, function (key, value) {
        	    $('select[name=cidade]').append('<option value=' + value.id + '>' + value.cidade + '</option>');
        	});

        });
    });

</script>
@stop

Running the application while selecting the state does not show the cities but the text "Select a city" is displayed. Could you help me? Ah for test I passed a direct state id in query.

2 answers

1

I added an Alert on the return of the $.get function as per.

Code below:

< script type = "text/javascript" >

  $('select[name=estado]').change(function() {

    var idEstado = $(this).val();

    $.get("{{ action ('CidadesController@getCidades') }} ", function(cidades) {

      alert(cidades)

      $('select[name=cidade]').empty();
      $('select[name=cidade]').append("<option value='' disabled selected style='display:none;'>Selecione uma cidade</option>");

      $.each(cidades, function(key, value) {
        $('select[name=cidade]').append('<option value=' + key + '>' + value + '</option>');
      });

    });

  }); < /script>

The message I get is: "This company does not exist!". I don’t know why but the place where I defined this text was in the class Empresascontroller.

Empresascontroller

class EmpresasController extends Controller
{
    public function index()
    {
        $empresas = Empresa::all();
        return view('empresa.index')->with('empresas', $empresas);
    }

    public function create()
    {
        $estados = Estado::all();
        return view('empresa.create')->with('estados', $estados);
    }

    public function edit($id){

        $empresa = Empresa::find($id);
        if(empty($empresa)){
            return 'Esta empresa não existe!';
        }
        return view('empresa.edit')->with('e', $empresa);
    }

    public function show($id)
    {
        $empresaDetails = Empresa::find($id);
        if(empty($empresaDetails)){
            return 'Esta empresa não existe!';
        }
        return view('empresa.show')->with('e', $empresaDetails);
    }

}

Is the route correct?

  • This is a new question... should be posted again and not here. If the answer is correct for the topic in question, mark as answered and start a new topic. I suggest, however, that you review your code piece by piece and try to divide the functions. Because the Company has nothing to do with the city and state, even if it has a city and a state, because the consultation it is doing is independent of the company. " Divide and Conquer!" I hope I helped. Abs

0

The script should look like this:

@section('post-script')
<script type="text/javascript">
    [...]

    $.each(cidades, function (key, value) {
        $('select[name=cidade]').append('<option value=' + key + '>' + value + '</option>');
    });
    [...]

</script>
@stop

key instead of value id.; and

value instead of city value..

For it is receiving within the function the field and not the object.

I hope I’ve helped.

  • I put a Alert(cities) on the return of function $.get. The cities parameter is bringing the phrase "This company does not exist". Well, where I defined this type of text was in the class Empresascontroller

  • Right, so there must be some filter before with respect to the company you are blocking. Try to do it in pieces and see that the code above works. = ) And just one comment, it would be a ** Alert(city)**... but as neither cities is bringing up the question is before that. Anyway with the above code, when it is working, it will fill your select correctly. Abs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.