Laravel 4:如何为嵌套资源编写正确的嵌套控制器? [英] Laravel 4: how to write the correct nested controller for nested resource?
问题描述
在Laravel 4中,我希望创建一组如下所示的静态资源:
In Laravel 4, I wish to create a set of restful resources as follows:
http://localhost/posts/1/comments
http://localhost/posts/1/comments/1
http://localhost/posts/1/comments/1/edit
...
因此,我创建了两个控制器: PostsController 和 CommentsController (在同一层上),路由如下所示:
...
So I created two controllers: PostsController and CommentsController (on the same layer), and the routes are written as below:
Route::resource('posts', 'PostsController');
Route::resource('posts.comments', 'CommentsController');
我还在/views/comments/index.blade.php中创建了一个引用路由的链接:posts.comments.create
I also created a link in /views/comments/index.blade.php referring to routes: posts.comments.create
{{ link_to_route('posts.comments.create', 'Add new comment') }}
这是我遇到的问题:
当我访问http://localhost/posts/1/comments
时,页面抛出 MissingMandatoryParametersException ,表明:
When I visit http://localhost/posts/1/comments
, the page throws MissingMandatoryParametersException, indicating:
缺少一些必需参数("posts")来生成路线"posts.comments.create"的URL.
如何解决该问题,以及如何知道该解决方案是否也适用于CommentsController中的create和edit方法?
How can I fix the problem, and how can I know whether the solution also applies for the create and edit methods in CommentsController?
例如
public function index()
{
$tasks = $this->comment->all();
return View::make('comments.index', compact('comments'));
}
public function create()
{
return View::make('comments.create');
}
public function show($post_id,$comment_id)
{
$comment = $this->comment->findOrFail($comment_id);
return View::make('comments.show', compact('comment'));
}
推荐答案
我在两个项目中使用了嵌套控制器,很喜欢它们.问题似乎出在您的控制器和路由链接中.
I'm using nested controllers in two projects, love them. The problem seems to be in your controller and route link.
在CommentController中,缺少$ post_id.做这样的事情:
In the CommentsController, the $post_id is missing. Do something like this:
public function create($post_id)
{
return View::make('comments.create')
->with('post_id', $post_id);
}
在创建到嵌套控制器的链接时,必须提供所有祖先的ID.在这种情况下,$ post_id再次丢失.如果尚未显示,则可能必须使其可用.
When creating links to a nested controller, the ID's of all of the ancestors must be provided. In this case the $post_id is again missing. You may have to make it available to your view if it's not already.
{{ HTML::linkRoute('posts.comments.create', 'Add new comment', $post_id) }}
这篇关于Laravel 4:如何为嵌套资源编写正确的嵌套控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!