Hey, my book is finally available. Find it here.  Eloquent Beyond The Basics!

How to make inputs show old value in blade after validation error

Apr 2, 2022

When a validation error occurs, by default, the form inputs will not keep the values they had before the submission. This makes for a terrible user experience since the user will need to reenter the information. Fortunately, Laravel offers a very simple way to fix this.

We can set the value to our inputs in our blade template with the help of the old helper.

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

If the value is not present, the old helper will return null, but if that's not what we want, we can pass a default to this helper.

<input type="text" name="username" value="{{ old('username', 'default value') }}">

As you can see here, in case the old value doesn't exist, the input's value will be set to default value. This is especially useful in editing pages where we already have a value, but we still want to show the old value, so the user doesn't need to retype it.

Use old value on selects

Selects are a little different because we can not set the type directly like in other inputs. However, you can still use the old helper to set the selected value. We just need to compare the old value to the current option and set the selected property if the value matches. Here is an example:

<select name="car" id="cars">
  <option value="volvo" {{ "volvo" === old('car') ? 'selected' : '' }}>Volvo</option>
  <option value="saab" {{ "saab" === old('car') ? 'selected' : '' }}>Saab</option>
  <option value="mercedes" {{ "mercedes" === old('car') ? 'selected' : '' }}>Mercedes</option>
  <option value="audi" {{ "audi" === old('car') ? 'selected' : '' }}>Audi</option>
</select>

And that it's it, that's how you use the old helper method to improve your website's user experience.