gpt4 book ai didi

php - 拉维尔 4 : how to write the correct nested controller for nested resource?

转载 作者:可可西里 更新时间:2023-10-31 22:12:36 28 4
gpt4 key购买 nike

在 Laravel 4 中,我希望创建一组 restful 资源如下:

http://localhost/posts/1/comments   
http://localhost/posts/1/comments/1
http://localhost/posts/1/comments/1/edit

...
所以我创建了两个 Controller :PostsControllerCommentsController(在同一层),路由写成如下:

Route::resource('posts', 'PostsController');

Route::resource('posts.comments', 'CommentsController');

我还在/views/comments/index.blade.php 中创建了一个引用路由的链接:posts.comments.create

{{ link_to_route('posts.comments.create', 'Add new comment') }}

这是我遇到的问题:

当我访问http://localhost/posts/1/comments时,页面抛出MissingMandatoryParametersException,提示:

缺少一些强制参数(“posts”)来为路由“posts.comments.create”生成 URL。

我怎样才能解决这个问题,我怎么知道这个解决方案是否也适用于 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'));

}

最佳答案

我在两个项目中使用了嵌套 Controller ,非常喜欢它们。问题似乎出在您的 Controller 和路由链接上。

在 CommentsController 中,缺少 $post_id。做这样的事情:

public function create($post_id)
{
return View::make('comments.create')
->with('post_id', $post_id);
}

创建嵌套 Controller 的链接时,必须提供所有祖先的 ID。在这种情况下,$post_id 再次丢失。如果还没有,您可能必须让它对您的 View 可用。

{{ HTML::linkRoute('posts.comments.create', 'Add new comment', $post_id) }}

关于php - 拉维尔 4 : how to write the correct nested controller for nested resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633898/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com