【问题标题】:Laravel 4: how to write the correct nested controller for nested resource?Laravel 4:如何为嵌套资源编写正确的嵌套控制器?
【发布时间】:2013-05-19 10:58:43
【问题描述】:

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

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

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

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

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

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

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

这是我遇到的问题:

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

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

我该如何解决这个问题,我如何知道该解决方案是否也适用于 CommentsController 中的 create 和 edit 方法?

例如

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

    }

【问题讨论】:

    标签: php laravel laravel-4 restful-url


    【解决方案1】:

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

    在 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) }}
    

    【讨论】:

    • 谢谢!我在编写重定向时遇到了另一个问题::路由如下:return Redirect::route('posts.comments.create')->with('post_id',$post_id) ->withInput() ->withErrors($validation) ->with('message', 'There were validation errors.'); 它仍然抛出相同的异常,有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2013-12-01
    • 2013-05-25
    相关资源
    最近更新 更多