Reputation: 95
I have problem with build select in Laravel blade and use only two types values from database
I have column in my migraton:
$table->enum('contact_way', ['email', 'phone']);
I have to use it in my blade form to update, I use simple @if statement but it is not good
<select class="form-control" name="contact_way">
@if ($customer_event->contact_way === "email")
<option value="email" selected>Kontakt e-mail</option>
<option value="phone" >Kontakt telefoniczny</option>
@else
<option value="email" >Kontakt e-mail</option>
<option value="phone" selected>Kontakt telefoniczny</option>
@endif
</select>
I want to use foreach staement where I use this to things and check witch one is correct and this show like selected but I don't know how to do it
Upvotes: 1
Views: 21413
Reputation: 29278
You shouldn't have to define your <option>
twice. Give this a try:
<select class="form-control" name="contact_way">
@foreach(["email" => "Kontakt e-mail", "phone" => "Kontakt telefoniczny"] AS $contactWay => $contactLabel)
<option value="{{ $contactWay }}" {{ old("contact_way", $customer_event->contact_way) == $contactWay ? "selected" : "" }}>{{ $contactLabel }}</option>
@endforeach
</select>
This would generate your select
with two options, each with a $contactWay
for the value=""
attribute and a $contactLabel
for the actual HTML. Also, would default your selected value to whatever was input last, or the value from $customer_event->contact_way
Upvotes: 2
Reputation: 261
In your model:
protected $contact_way = ['email', 'phone'];
now loop as
@foreach($customer_event['contact_way']'as $contact)
<option value="{{$contact}}" @if($contact == $customer_event->contact_way) "selected" @endif >{{ $contact}}</option>
@endforeach
Upvotes: 3
Reputation: 35337
There's many ways to do this, but look at your code. You rewrite the entire options just to change one word: selected.
Just write a condition to handle that word (using ternary operators):
<option value="email" <?= $customer_event->contact_way === 'email' ? 'selected' : '' ?>>Kontakt e-mail</option>
<option value="phone" <?= $customer_event->contact_way === 'phone' ? 'selected' : '' ?>>Kontakt telefoniczny</option>
I don't see any need for a foreach loop with only two elements, but you could create an array of options to loop through if you really wanted.
Upvotes: 3