2014-05-09 30 views
3

因此,我写了一个嵌套资源的简单应用程序:帖子和评论。当然,职位是父母,评论是儿童,每个职位与一个职位相关。够简单。现在我要评论索引(和创建,POST)页面生活在posts/{post_id}/comments,更新(PUT)生活在/posts/{post_id}/comments/{comment_id}。所以,我想这一点:如何在Laravel 4上路由儿童资源?

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

Route::group(array('prefix' => 'posts/{post_id}'), function() { 
    Route::resource('comments', 'CommentsController'); 
}); 

但由于路线名称注册为posts.{post_id}.comments.create将无法​​正常工作。基本上,post_id占位符被视为路线的一部分,并且不是整洁的。任何方式做这个很好,或者我应该只写一个一个路由,并摆脱组/路线::资源/前缀的东西?

回答

6

您可以像这样使用嵌套资源;

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

当你php artisan routes你会看到你的新路线;

+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+ 
| Domain | URI            | Name     | Action        | Before Filters | After Filters | 
+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+ 
|  | GET|HEAD posts         | posts.index   | [email protected]    |    |    | 
|  | GET|HEAD posts/create       | posts.create   | [email protected]    |    |    | 
|  | POST posts          | posts.store   | [email protected]    |    |    | 
|  | GET|HEAD posts/{posts}       | posts.show    | [email protected]    |    |    | 
|  | GET|HEAD posts/{posts}/edit      | posts.edit    | [email protected]    |    |    | 
|  | PUT posts/{posts}        | posts.update   | [email protected]    |    |    | 
|  | PATCH posts/{posts}        |      | [email protected]    |    |    | 
|  | DELETE posts/{posts}       | posts.destroy   | [email protected]   |    |    | 
|  | GET|HEAD posts/{posts}/comments     | posts.comments.index | [email protected]   |    |    | 
|  | GET|HEAD posts/{posts}/comments/create   | posts.comments.create | [email protected]   |    |    | 
|  | POST posts/{posts}/comments      | posts.comments.store | [email protected]   |    |    | 
|  | GET|HEAD posts/{posts}/comments/{comments}  | posts.comments.show | [email protected]   |    |    | 
|  | GET|HEAD posts/{posts}/comments/{comments}/edit | posts.comments.edit | [email protected]   |    |    | 
|  | PUT posts/{posts}/comments/{comments}   | posts.comments.update | [email protected]   |    |    | 
|  | PATCH posts/{posts}/comments/{comments}   |      | [email protected]   |    |    | 
|  | DELETE posts/{posts}/comments/{comments}  | posts.comments.destroy | [email protected]   |    |    | 
+--------+-------------------------------------------------+------------------------+------------------------------------+----------------+---------------+ 
+0

当我在CommentsController'''index($ posts){echo $ posts}'''中写这样的东西时,它不显示任何东西? –

+0

我的不好。它工作正常。 –