Reputation: 147
I'm creating an edit form in Laravel and I would like to select the selected (database) value in Select Dropdown. I'm doing it now as below. Is the right method or anything better is possible? I'm using Laravel 5.4.
<select class="form-control" id="type" name="type">
<option value="admin" @if($user->type==='admin') selected='selected' @endif>Admin</option>
<option value="telco" @if($user->type==='telco') selected='selected' @endif>Telco</option>
<option value="operator" @if($user->type==='operator') selected='selected' @endif>Operator</option>
<option value="subscriber" @if($user->type==='subscriber') selected='selected' @endif>Subscriber</option>
</select>
Upvotes: 0
Views: 9287
Reputation: 1203
You can also use ternary operator instead of if
<select class="form-control" id="type" name="type">
<option value="admin" {{($user->type ==='admin') ? 'selected' : ''}}> Admin </option>
<option value="telco" {{($user->type ==='telco') ? 'selected' : ''}}> Telco </option>
<option value="operator" {{($user->type ==='operator') ? 'selected' : ''}}> Operator </option>
<option value="subscriber" {{($user->type ==='subscriber') ? 'selected' : ''}}> Subscriber </option>
</select>
Upvotes: 1
Reputation: 610
I would say that this is a normal approach.
If you want to make it more "friendly" it would take some overhead, for example using a @foreach loop to loop an array that would create all the options for the select, something like this :
$arr = ['admin','telco','operator','subscriber'];
@foreach($arr as $item)
<option value="{{ $item }}" @if($user->type=== $item) selected='selected' @endif> {{ strtoupper($item) }}</option>
@endforeach
Upvotes: 1