Laravel

[Laravel] How to Preserve Form Input/Selection Values Using the old Helper

In Laravel’s registration/update form screen, if you input text in an input field or make a selection in a select field, and a validation error occurs upon submission, the form may be reloaded with all fields reset to empty. This article explains how to retain the input/selected values using the old helper.

Registration Form Screen Using the old Helper (View File)

* When validation is performed after input/selection in the registration form screen (view file), the entered/selected values are retained (set in the value attribute).

input tag

Set the following in the value attribute:
old('name attribute')

<input type="text" name="address" value="{{ old('address') }}">

textarea tag

Set the following between the opening and closing textarea tags:
old('name attribute')

<textarea name="bikou">{{ old('bikou') }}</textarea>

select tag

If a value has been selected, apply selected to the corresponding option tag.

<select name="sex">
<option value="">Select gender</option>
<option value="man" @if( old('sex') === 'man' ) selected @endif>Male</option>
<option value="woman" @if( old('sex') === 'woman' ) selected @endif>Female</option>
</select>

Update Form Screen Using the old Helper (View File)

* This is mostly the same as the registration form screen, but in the update form, the default value before validation is also set in the value attribute.

input tag

Set the following in the value attribute:
old('name attribute', value retrieved from the database)

<input type="text" name="address" value="{{ old('address', $user->address) }}">

textarea tag

Set the following between the opening and closing textarea tags:
old('name attribute', value retrieved from the database)

<textarea name="naiyo">{{ old('bikou', $user->bikou) }}</textarea>

select tag

If there is a default value or a previously selected value, apply selected to the corresponding option tag.

<select name="sex">
<option value="">Select gender</option>
<option value="man" @if( old('sex') === 'man' ) selected @endif>Male</option>
<option value="woman" @if( old('sex') === 'woman' ) selected @endif>Female</option>
</select>

<select name="sex">
<option value="">Please select</option>
<option value="man" @if( old('sex', $user->sex) === 'man' ) selected @endif>Male</option>
<option value="woman" @if( old('sex', $user->sex) === 'woman' ) selected @endif>Female</option>
</select>

* Verified on Laravel version 6.x

* Use at your own risk if reusing this implementation.