0

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>

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This makes sense!
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.