加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel 4:如何为嵌套资源编写正确的嵌套控制器?

发布时间:2020-12-14 19:44:01 所属栏目:大数据 来源:网络整理
导读:在Laravel 4中,我希望创建一组如下的宁静资源: http://localhost/posts/1/comments http://localhost/posts/1/comments/1 http://localhost/posts/1/comments/1/edit … 所以我创建了两个控制器:PostsController和CommentsController(在同一层上),路由编写
在Laravel 4中,我希望创建一组如下的宁静资源:

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


所以我创建了两个控制器:PostsController和CommentsController(在同一层上),路由编写如下:

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.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'));  

    }

解决方法

我在两个项目中使用嵌套控制器,喜欢它们.问题似乎在您的控制器和路由链接中.

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

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

创建指向嵌套控制器的链接时,必须提供所有祖先的ID.在这种情况下,$post_id再次丢失.您可能必须将其提供给您的视图(如果尚未提供).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读