How popular to select according to other select data in Laravel?

Asked

Viewed 125 times

-1

I would like to make a dynamic select so that when I choose the state, load the cities of that state into the other select.

City and state are in different tables, but have foreign key, so when I register a city, it is automatically identified which state it belongs to.

It has already been made Belong to relation of city to state and has Many of state to city.

Select on Slide is like this:

  <div class="row gy-3">
            <div class="col-6">
                <label class="form-label">Estado: </label>
                <select class="form-select form-select-md" name="unifed" class="form-control" id="uf_id">
                    <option selected>Selecione</option>
                    @foreach($ufs as $uf)
                        <option value="{{ $uf['id'] }}"> {{ $uf['sigla'] }} </option>
                    @endforeach
                </select>
            </div>

      
            <div class="col-6">
                <label class="form-label">Cidade: </label>
                <select class="form-select form-select-md" name="cidade" class="form-control" id="cidade_id">
                    <option selected>Selecione</option>
                    @foreach($cidades as $cidade)
                        <option value="{{ $cidade['id'] }}"> {{ $cidade['nome'] }}  </option>
                    @endforeach
                </select>
            </div>  

What do I need to change? For in the city select is showing all cities.

I have tried several solutions but none worked.

If anyone can help me, I appreciate it now. This is really very important.

1 answer

0

I use Jquery and Ajax a lot to do this kind of service, I do not guarantee you is the best solution, possibly you can handle this information in the javascript itself, without necessarily making a request in the database for each new event, but if you want to use I will send you step by step as I did in a situation similar to me.

First you should do a route on the web.php to request cities.

    Route::post('/encontrar-cidade', 'CityController@findCity');

Here we will do the function that will be performed in the controller to find the cities of the selected state, in this case it will return the cities with the same ID of the state that will be sent by ajax, I named it as "state_id", and the foreign key is the ID you put in the database.

public function findCity(Request $request) {
    $cities = SeuModelDeCidade::all();
    return $cities->where('chave_estrangeira_estado_id', '=', $request['estado_id']);
}

The view went like this:

<div class="col-6">
    <label class="form-label">Estado: </label>
    <select data-url="{{ url('/econtrar-cidade') }}" data-token="{{ csrf_token() }}" onchange="changeCity(this)" name="unifed" id="uf_id">
        <option selected>Selecione</option>
        @foreach($ufs as $uf)
            <option value="{{ $uf['id'] }}"> {{ $uf['sigla'] }} </option>
        @endforeach
    </select>
</div>
<div class="col-6">
    <label class="form-label">Cidade: </label>
    <select class="form-select form-select-md" name="cidade" class="form-control" id="cidade_id">
        <option selected>Selecione</option>
    </select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js"></script>
<script>
function changeCity(response) {
    $.ajax({
        url: $(response).data('url'),
        type: 'post',
        data: {_method: 'post', _token: $(response).data('token'), state_id: response.value},
        success: function(res) {
            $("#cidade_id").empty();
            $.each( res, function(a, b) {
                $('#cidade_id').append($('<option>', {value: b['id'], text: b['nome']}));
            });
        },
        error: function(){
            console.log('error');
        },
    });
}
</script>
  • Thank you! Friend, I understood the code and its logic being that now the list of cities is empty. Regardless of whether I choose a state, the list of cities isn’t pulling the cities from the bank. The public Function findcity I put in the City Controller. This correct?

  • Vitória, the controller you put is indifferent, because the route will redirect to the controller you indicated, and this will perform the function, so I do not believe this is the problem. The error could be in many places, I would have to have more information to tell you the reason for the error. First, it is running the Function changeCity? (gives a console.log in the function to check). If so, is it falling into the controller’s findCity function? (you can use php dd() to find out). And tell me the error that’s happening

  • lacked an "n" in select, I wrote "econtrar-city" instead of "find-city", maybe the mistake is this.

Browser other questions tagged

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