Laravel 4:为带有动态加载数据的模型构建表单


Laravel 4: Building forms for models with eager loaded data

使用laravel 4,您可以绑定到窗体中的模型。

例如,下面的代码将绑定一个表单到Post。

$post = Post::find(1);
Form::model($post, [
    'action' => ['PostController@update', $post->id], 
    'method' => 'PUT'
])

据我所知,要保持一个数据库结构良好,我将有一个单独的表的类别。因此,下面我将急于加载我的类别到$post。

$post = Post::with('categories')->find(1);

我想编辑表单中的类别。但如何?

我想象html输出最终会是这样的:

<input type="text" name="categories[0][value]" />

…但是,什么才是正确的方法呢?我想这是非常常见的,因为只要您的内容类型存储在多个表中,您就会遇到它。

我对用户/角色做了类似的事情,我认为这与你的帖子/类别有类似的关系。

在你的PostController创建/编辑动作中,发送所有类别的对象:

$categories = Category::all();
return View::make('post.edit')->with(array('categories' => $categories)) // truncated for brevity

In your View:

@foreach ($post->categories as $category)
    {{ Form::checkbox('p_categories[]', $category->id, false, array('id' => $category->id)) . Form::label($category->id, $category->name) }}<br />
@endforeach

在你的PostController store/update操作中:

$post->categories()->sync(Input::get('p_categories'));

还有,这里有一篇关于同样概念的文章写得很好。简化多对多关系

希望这对你有帮助!