Binding Laravel form with one to one relationship

I have an account model that has a polymorphic relationship to the Address model. This is configured as an individual shutdown, configured like this:


public function address()
    return $this->morphOne('Address', 'hasAddress', 'add_hasaddress_type', 'add_hasaddress_id', 'act_id');



public function hasAddress()
    return $this->morphTo('hasAddress', 'add_hasaddress_type', 'add_hasaddress_id');


In my form to edit an account, I also have address fields. I can link my account object quite simply:

{{ Form::model($account, array('route' => array('accounts/edit', $account->act_id), 'method' => 'put')) }}
    {{ Form::label('act_name', 'Account Name:') }}
    {{ Form::text('act_name', Input::old('act_name')) }}


and fills in the fields correctly. But how do you fill in the address fields? From what I've researched, I need to do:

{{ Form::text('address.add_city', Input::old('address.add_city')) }}


To access the values ​​of the relationship, but that won't work.

I have also tried

{{ Form::text('address[add_city]', Input::old('address[add_city]')) }}


as suggested by SO of the same name. I've tried both of these with and without the old input. Does this just not work with mimorphic relationships or am I doing something wrong?

Also, how do you handle these forms in the controller?

There is nothing about relationships in the documentation associated with the model, and searches mostly cause people to require one-to-many binding.


source to share

1 answer

It works with any * -to-one relationship (for many-to-many, i.e. a set of models it won't work):

// prepare model with related data - eager loading
$account = Account::with('address')->find($someId);

// or lazy loading
$account = Account::find($someId);

// view template
{{ Form::model($account, ...) }}
  Account: {{ Form::text('acc_name') }}
  City: {{ Form::text('address[add_city]') }}
{{ Form::close() }}


No need for Input::old

or at all, null

enough as default. Laravel will fill in the data in this order (The docs are wrong here! ):

1. old input
2. bound data
3. value passed to the helper


Remember that you have to load the relation (dynamic invocation will not work in this case).

One more thing - processing the data later - Laravel doesn't automatically moisturize the associated model, so you need something like:

$accountData = Input::only(['acc_name', ... other account fields]);
// or
$accountData = Input::except(['address']);
// validate etc, then:

$addressData = Input::get('address');
// validate ofc, then:




All Articles