mrhn
mrhn

Reputation: 18926

Laravel Formbuilder Modelbinding

I'm working with the following code. Trying to utilize the model binding effects of Laravel and the FormBuilder.

{!! Form::model($contact,['method' => 'PUT', 'url' => URL::route('contact.put', $contact),'accept-charset' => 'UTF-8', 'enctype' => 'multipart/form-data']) !!}

<div class="form-group">
    {!! Form::label('','First Name') !!}
    {!! Form::text('first_name','', ['class' => 'form-control','required' => 'required']) !!}
</div>

...

{!! Form::close() !!}

This is pretty stock code, which is taken from the older documentation, it will fine be able to update the information as intended, but there is no way i can get the model binding to fill the value of the Text Input Field first_name. The weird part is, if i create it in stock html code, like this:

<input type="text" class="form-control" name="first_name" id="first_name" value="{{$contact->first_name}}" required="required">

It will fill out the value fine, so what is missing?

Upvotes: 1

Views: 545

Answers (1)

Thomas Kim
Thomas Kim

Reputation: 15931

It's because you are passing in an empty string. Unless you have a predefined value that you want to set, you should pass a null value like this:

{!! Form::text('first_name', null, ['class' => 'form-control','required' => 'required']) !!}

Why is this happening?

This is the section of the code that populates the input's value:

public function getValueAttribute($name, $value = null)
{
    if (is_null($name)) {
        return $value;
    }
    if (! is_null($this->old($name))) {
        return $this->old($name);
    }
    if (! is_null($value)) {
        return $value;
    }
    if (isset($this->model)) {
        return $this->getModelValueAttribute($name);
    }
}

What you should focus on is the 3rd if statement. You are passing in an empty string, which is not a null value, so it assumes you know what you want to pass as the default value.

However, if you pass in a null value, it skips the 3rd if statement and moves onto the 4th if statement, which retrieves the value from the model.

Upvotes: 1

Related Questions