Share fields between the create and edit forms in Laravel

This is a simple one.

In your applications you are likely to have resources that you create and edit with forms. The create and edit forms are basically the same (with the fields being exactly the same) but work in a slightly different way.

In the create view you start with an empty form, while in the edit view you start with the form filled with the current data. But, in both views you’ll want the old input (aka the input that was just submitted) in case the validation fails and you are returned to the form.

So, if you want to write the fields only once and then share it with both views, this is a fairly clean way to do it:

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

If the field in the first parameter is not set, the old() helper function returns null or a value passed as the second parameter. Using an expression with the null coalescing operator as the second parameter give us the ability to still return null if neither of the previous values are set.

This works as expected in both views. In the create view, $user->email would not be set and null would be returned (and the field would be empty), in the edit view $user->email would be set and it would be returned. Except if old input exists, in that case the old input would returned.

You could also write it this way, to the same effect:

<input type="text" name="email" value="{{ old('email') ?? $user->email ?? null }}">