in my form i have a select and if i edit i want keep select the option i try with isset but i dont know how to use it in a select
this is my select:
<div >
<label for="id_raza">Raza</label>
<select id="id_raza" name="id_raza" placeholder="Raza">
@foreach ($razas as $raza)
<option value="{{$raza->id}}">{{ $raza->Nombre}}</option>
@endforeach
</select>
</div>
my controller:
public function edit($id)
{
//
$mascota=Mascota::findOrFail($id);
$razas = Raza::all();
$propietarios = Propietario::all();
return view('mascota.edit', compact('mascota', 'razas', 'propietarios'));
}
my table:
{
Schema::create('mascotas', function (Blueprint $table) {
$table->id();
$table->foreignId('id_raza')
->nullable()
->constrained('razas')
->nullOnDelete()
->cascadeOnUpdate();
$table->timestamps();
});
}
CodePudding user response:
Since mascotas
has a id_raza
, this value is needed to be able to set the selected
option.
@foreach ($razas as $raza)
@if (!empty($moscatas->id_raza) && $moscatas->id_raza == $raza->id)
<option value="{{$raza->id}}" selected>{{ $raza->Nombre}}</option>
@else
<option value="{{$raza->id}}">{{ $raza->Nombre}}</option>
@endif
@endforeach
CodePudding user response:
You can also do it like this,
<option value="{{ $raza->id }}" {{
$raza->id == $moscatas->id_raza ?
'selected' : '' }}>
{{ $raza->Nombre}
</option>