Reputation: 12568
I am trying to use 'old' in a Laravel 5 app to pre-populate a select form on an edit route like this...
<select id="category" name="category" required>
<option value="">Select</option>
<option value="animal" @if (old('category') == "animal") {{ 'selected' }} @endif>Animal</option>
<option value="vegetable" @if (old('category') == "vegetable") {{ 'selected' }} @endif>Vegetable</option>
<option value="mineral" @if (old('category') == "mineral") {{ 'selected' }} @endif>Mineral</option>
</select>
This works well and keeps the selected option if a validation fails, but I am trying to make it work so that it pre-populates when the page first loads.
How do I determine if this is the first load of the edit page, or if it has reloaded after a validation failure? Or is there a better way to do this?
Upvotes: 1
Views: 201
Reputation: 4499
Lets imagine you have sent the category
value as $category
.
So in every <option>
tag,
<option value="animal"
{{ old('category') == 'animal' ? ' selected' :
$category == 'anumal' ? ' selected' : '' }}>
Animal
</option>
This is what is going on there:
if there is an old value and its matching, select this,
else if the original value is matching select this,
else do nothing.
Upvotes: 2
Reputation: 3030
Use the second parameter of the old function with a default/initial value:
<option value="animal" @if (old('category', 'animal') == "animal") {{ 'selected' }} @endif>Animal</option>
The second parameter will be returned as the function result if an old value cannot be found in the flashed input.
Upvotes: 1