I have a dropdown called designation, where a user will select one of it, and after submitting it, if there is some error then I want to select the selected designation.
I am using this in laravel 5.4.
Controller
$info = DB::table("designation")
->where('status','=',1)
->pluck("name","id");
return view('regUser.add',['check' => 'userList','designation' => $info]);
View Files
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
@foreach ($designation as $key => $value)
<option value="{{ $key }}" />{{ $value }}</option>
@endforeach
</select>
@if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
@endif
</div>
Now if the validator found some error then I want to select the previously selected one. How can i achive this in laravel 5.4.
After submiting the form it comes to addUserInformation function, where I validate the user information which have this piece of code
public function addUserInformation(Request $request){
$this->validate($request, [
'name' => 'required|string|min:5',
'email' => 'required|string|email|unique:users,email',
'designation' => 'required|exists:designation,id',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'userimage' => 'required|image',
]);
$selectedID = $request->input('designation');
}
Larvel passes the inputs back on validation errors. You can use the old
helper function to get the previous values of form. A simple comparison should do the trick.
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
@foreach ($designation as $key => $value)
<option value="{{ $key }}" {{ old('designation') == $key ? 'selected' : ''}}>{{ $value }}</option>
@endforeach
</select>
@if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
@endif
</div>
You have to maintain the state of old input by using return redirect()
like:
return redirect('form')->withInput();
Retrieving Old Data
To retrieve flashed input from the previous request, use the old method on the Request instance.
$oldDesignation = Request::old('designation');
and check it like:
@foreach ($designation as $key => $value)
$selected = '';
@if( $value == $oldDesignation )
$selected = 'selected="selected"';
@endif
<option value="{{ $key }}" {{ $selected }} />{{ $value }}</option>
@endforeach
Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With