Casey
Casey

Reputation: 1981

Laravel Form Model Binding with Relationships

Is it possible to bind a form with a model that has relationships? For example I have a Order model that has a one to many with a Details model. That would save a lot of time with

@foreach($order->details as $detail)
{{ Form::text('product_name', Input::old('product_name') ? Input::old('product_name') : detail->product_name)
@endforeach

Upvotes: 4

Views: 7735

Answers (2)

The Alpha
The Alpha

Reputation: 146191

For a one-to-one relation it's possible to use something like this:

Form::text('detail[product_name]')

In this case $order->detail->product_name will be populated in the given text box if an instance of Order model is bound to the from using Form::model($order) with the related model Detail but it may not possible for one-to-many because simply there will be a collection and you need a loop.

Upvotes: 10

Aurel
Aurel

Reputation: 3740

To complete the answer of @WereWolf..

  • Make an array of product_name detail_names
  • Input class allow you to access nested array by dot notation, eg: orders.1.product_name
  • Don't forget the second argument of Input::old() or Input::get() is the default value, so you can specify the DB value and avoid conditional test..

.

Form::text('detail_names['.$detail->id.']', Input::old('detail_names.'.$detail->id, $detail->product_name))

In your controller, something like that:

foreach(Input:get('detail_names') as $id => $product_name)
{
    //...
}

Hope this will help you to save a bit of time.

Upvotes: 3

Related Questions