如何使用带有数组作为名称属性的Laravel表单模型绑定? [英] How to use Laravel form model binding with array as name attribute?
问题描述
我想在Laravel中使用表单模型绑定.以下(简化的)示例可以正常工作:
I want to use form model binding in Laravel. The following (simplified) example works fine:
{{ Form::model($user, array('class'=>'form-horizontal')) }}
{{ Form::token() }}
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email') }}
{{ Form::close() }}
但是,我想在name
属性中使用数组,这是当今非常标准的方法.换句话说,使用user[email]
作为字段名称,这样我就可以在后端的一个数组中获取所有表单元素.
However, I want to use arrays in the name
attributes, as is pretty standard nowadays. In other words, have user[email]
as the field name, so that I get all the form elements in one array in the backend.
使用模型绑定可以做到吗?当我使用{{ Form::text('user[email]') }}
时,电子邮件没有填写.我尝试在Form::model
函数中添加array('user'=>$user)
,以防它需要嵌套值,但没有运气.
Is this possible with model binding? When I use {{ Form::text('user[email]') }}
the email does not get filled in. I tried adding array('user'=>$user)
in the Form::model
function in case it needed a nested value, but no luck.
推荐答案
Form::model(array('user' => $user))
是正确的解决方案,但不幸的是,表单模型绑定的实现非常糟糕,因为它不容易在嵌套的,混合的数组集合上工作和对象.参见 https://github.com/laravel/framework/pull/5074
Form::model(array('user' => $user))
is the correct solution, BUT unfortunately the implementation of form model binding is pretty bad as it does not easily work on a nested, mixed set of arrays and objects. See https://github.com/laravel/framework/pull/5074
您可以尝试Form::model(array('user' => $user->toArray()))
或Form::model((object) array('user' => $user))
.
这篇关于如何使用带有数组作为名称属性的Laravel表单模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!