How to populate model field values in Edit form in Laravel 5.3

You have started with Laravel 5.3, and you are not using the HTML/Form Package whose examples you will find all over the internet to make CRUD functionality, you may be wondering as how to fetch the values in Edit form.

You cannot just replace the value=”{{ old(field_name) }}” since you also need the validation to show us the earlier entered values which.

Solution is to use the second parameter on old() function, so the value attribute of field becomes {{ old(field_name, $model->field_name) }} which will work in both cases. It will populate the field with initial model value and validate and fill the earlier entered value in case of failed validation.

I am assuming that you have passed the fetched model in $user variable and passed it from controller to the view.

(app/Http/controllers/UserController.php)

public function getProfile()
{
   return view('user.edit', ['user' =>  Auth::user()]);
}

 

So, the form looks like

(user/edit.blade.php)

<form class="form-horizontal" role="form" method="POST" action="{{ route('put_profile') }}">
     <input type="hidden" name="_method" value="PUT" />
     {{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
     <label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
         <input id="name" type="text" class="form-control" name="name" value="{{ old('name', $user->name) }}" autofocus>
         @if ($errors->has('name'))
            <span class="help-block">
            <strong>{{ $errors->first('name') }}</strong>
            </span>
        @endif</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
     <label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
          <input id="email" type="text" class="form-control" name="email" value="{{ old('email', $user->email) }}" >

          @if ($errors->has('email'))
          <span class="help-block">
               <strong>{{ $errors->first('email') }}</strong>
           </span>
          @endif</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
     <button type="submit" class="btn btn-primary">Save</button></div>
</div>
</form>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s