I'm trying to make a form that contains 3 inputs. The first one should let the user select a state. Now, based on that selection (selection of input 1), the second input should load data from a DB table that has a relationship with the selected state, and the third input doing the same but in relation of the second input selection.
I have no idea how to do it, though I've tried this way:
My view: (it's all wrong here, I guess the magic happens on the controller).
<div id="inputs-estado">
<div class="form-group">
{{-- Estados --}}
<label for="">Estado</label>
<select name="direccion" id="forma-estado" class="form-control dynamic" data-dependant="state">
@foreach ($estados as $estado)
<option value="{{ $estado->state }}">{{ $estado->state }}</option>
@endforeach
</select>
<br>
{{-- Municipio/Delegación --}}
<label for="">Ciudad</label>
<select name="direccion" id="form-ciudad" class="form-control dynamic" data-dependant="city">
@foreach ($estados as $estado)
<option value="{{ $estado->state }}">{{ $estado->state }}</option>
@endforeach
</select>
<br>
{{-- Colonia --}}
<label for="">Municipio</label>
<select name="direccion" id="form-municipio" class="form-control dynamic" data-dependant="municipality">
<option value="">Selecciona el municipio</option>
</select>
</div>
</div>
My controller:
public function fetch(Request $request)
{
$state_id = DB::connection('db_postalcodes')->table('city')->get();
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = DB::connection('db_postalcodes')
->table('city')
->where($select, $state_id->state_id)
->groupBy($dependent)
->get();
$output = '<option value="">Select ' . ucfirst($dependent) . '</option>';
foreach ($data as $row) {
$output .= '<option value="' . $row->$dependent . '">' . $row->$dependent . '</option>';
}
echo $output;
}
Also, I've got multiple tables with the data stored. So I guess I need to use some relationship functions in Laravel (but I don't know).