I want the select dropdown value to be selected in my edit form.
In my controller
public function edit($id)
{
$vedit = DB::table('vehicles')->where('id', $id)->first();
$cartype= DB::table('car_category')->pluck('cartype');
return view('vehicles.edit', compact('vedit','cartype'));
}
In view
{{ Form::label('Vehicle Type', 'Vehicle Type') }}
<select name="vehicle_type" class="form-control">
@foreach($cartype as $cartypes)
<option value="{{ $cartypes}}">{{ $cartypes}}</option>
@endforeach
</select>
How can I achieve this?
You can add selected
attribute if it's the choosen one like this :
{{ Form::label('Vehicle Type', 'Vehicle Type') }}
<select name="vehicle_type" class="form-control">
@foreach($cartype as $cartypes)
<option value="{{ $cartypes}}" {{ $cartypes == $vedit->vehicle_type ? 'selected' : ''}}>{{ $cartypes}}</option>
@endforeach
</select>
What version of Laravel are you using ? Looks like you're using Laravel Collective Form facade.
In that case, this should work fine:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, $vedit->vehicle_type ?: old('vehicle_type), ['class' => 'form-control']) !!}
Assuming $vedit->vehicle_type
is your previously stored vehicle type. So it will pre-select that when editing. In case of creating new, old('vehicle_type')
should persist the previously selected value on failed validations.
By calling pluck()
an array of values is already returned for the car types.
So just use it like this natively with Laravel Collective:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, null, ['class' => 'form-control']) !!}
Note, I have also changed your double curly braces. The double curly braces escape the output - given the Form
facade returns HTML code, you want this to be unescaped.
More info on generating drop down lists with Laravel Collective; https://laravelcollective.com/docs/5.4/html#drop-down-lists
Edit show currently selected value and old value if form fails validation:
{!! Form::label('Vehicle Type', 'Vehicle Type') !!}
{!! Form::select('vehicle_type', $cartype, old('vehicle_type', $vedit->vehicle_type), ['class' => 'form-control']) !!}