How to filter by state cities in Laravel?

Asked

Viewed 1,227 times

4

I made a filter in the Laravel and it works perfectly but nevertheless brings all the cities. It does not bring the specific cities of that state. I do not know if it is this filter that has to pass there in the controller of the Laravel, how do you make it work in jquery? I am using a Rest-Full web-service

I’m going through Postman like this: http://localhost/rep_php/public/api/municipios? filter[estados_id]=4

He returns to me all states: inserir a descrição da imagem aqui

Look at my tables and my controllers in LARAVEL. I still put JQUERY:

Municipios CONTROLLER

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Municipios;
class MunicipiosController extends Controller
{
  public function index()
  {
    $municipios = Municipios::with('estados')->get();
    return response()->json($municipios);
  }

  public function show($id)
  {
    print_r('teste');
    $municipios = Municipios::with('estados')->find($id);

    if(!$municipios) {
      return response()->json([
        'message'   => 'Não há resultados',
      ], 404);
    }

    return response()->json($municipios);
  }
}

MUNICIPIOS MODEL

namespace App;

use Illuminate\Database\Eloquent\Model;

class Municipios extends Model
{
  protected $fillable = ['nome','cep'];
  protected $primaryKey = 'municipios_id';

  public function estados()
  {
    return $this->belongsTo('App\Estados');
  }
}

MODEL STATES

namespace App;

use Illuminate\Database\Eloquent\Model;

class Estados extends Model
{
  protected $fillable = ['nome','sigla'];
  protected $primaryKey = 'estados_id';

  public function municipios()
  {
    return $this->hasMany('App\Municipios');
  }
}

CONTROLLER STATES:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Estados;

class EstadosController extends Controller
{
    //
    public function index ()
    {
      $estados = Estados::all();
      return response()->json($estados);
    }
}

ARCHIVE ROUTES:

use Illuminate\Http\Request;

Route::get('/', function () {
  return response()->json(['message' => 'Rep Api', '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');

TABLES MUNICIPIOS:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableMunicipiosTable extends Migration
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    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();
    });
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {
    Schema::dropIfExists('municipios');
  }
}

TABLE STATES:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableEstadosTable extends Migration
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    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();
    });
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {

    Schema::dropIfExists('estados');
  }
}

JQUERY:

 // outras funções de validação do formulário
  function retorna_estados()
  {
    var opcaoCadastro = "";
    $.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();

1 answer

1


I in Laravel 5.2 do so

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: remembering that on the route I use a prefix "logistica".

Controller

public function get_cidades($id)
{
    $comarca = DB::table('cidades')
      ->where('uf','=', $id)
      ->orderBy('name','asc')
      ->get();

    return Response::json($comarca);
}

Browser other questions tagged

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