What is the best practice to show old value when e

2019-04-24 07:34发布

问题:

I am writing the logic for an edit form and have some complications when displaying data in the inputs.

When I initially show the form, I show the records values like:

value="{{$dog->title}}"

Then when the form does not pass the validation I need to show the old input, so that user does not loose what he has already input. So I need to have a way to display old data like:

value="{{old('title')}}"

Because I need to input old data in case it exists, I ended up with this code:

value="{{$dog->title or old('title')}}"

And in controller I check if Request has old input, I assign the $dog var a null value.

I wanted to ask if that is considered an OK practice or is there a better and 'correct' way to do it?

回答1:

Function old have default parameter if no old data found in session.

function old($key = null, $default = null)

You can replace expression in template with

value="{{old('title', $dog->title)}}"


回答2:

I know this has already been answered but I thought i would leave a little snipet here for others in the future.

Setting old value on input as @ikurcubic posted:

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

Setting old value on select,radio button: write a small if statment to check if there is an old value if there is not then select the database value.

@php                                  
if(old('name') !== null){
    $option = old('name'); 
}
else{ $option = $database->value; }
@endphp

<select name="name">
   <option value="Bob" {{ $option == 'Bob' ? selected : '' }}>Bob</option>
   <option value="Jeff" {{ $option == 'Jeff' ? selected : '' }}>Jeff</option>
   <option value="Marly" {{ $option == 'Marly' ? selected : '' }}>Marly</option>
</select>

The same goes for radio buttons:

@php                                  
    if(old('gender') !== null){
        $option = old('gender'); 
    }
    else{ $option = $database->value; }
@endphp

<input type="radio"  name="gender" value="M" {{ $option == "M" ? 'checked' : '' }} />
<label>Male</label>

<input type="radio"  name="gender" value="F" {{ $option == "F" ? 'checked' : '' }} />
<label>Female</label>

Setting old value of input with an array name e.g name[]:

value="{{ old('name.0) }}"

This will give you the old value of the input with an index of 0

I have tested this and it works, I hope it helps someone.



回答3:

There is nothing wrong with the way you are doing things as Laravel gives multiple ways to handle the situation you're describing.

What I would suggest is using the Laravel Collective Form and HTML packages to build your form. This package will automatically handle binding old request values to your form if validation fails

https://laravelcollective.com/docs/5.2/html