Question:
I am starting my studies on Laravel . My project is a simple registration of clients where I would like to make a combo of States and Cities.
Here are 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');
}
}
CITIES MODEL
<?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 REGISTRATION
<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 when selecting the state, cities are not shown but the text "Select a city" is displayed. can you help me? Ah for testing I passed a state id directly in the query.
Answer:
Added an alert on the return of the $.get function accordingly.
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 doesn't exist!" . I don't know why but the place where I defined this text was in the CompaniesController class.
Controller Companies
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?