Laravel 4: how to write the correct nested controller for a nested resource?

In Laravel 4, I want to create a set of sedative resources as follows:

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

...
Therefore, I created two controllers: PostsController and CommentsController (at the same level), and the routes are written as follows:

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

I also created a link in /views/comments/index.blade.php, citing the routes: posts.comments.create

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

Here is the problem I met:

When I visit http://localhost/posts/1/comments , the page throws a MissingMandatoryParametersException , indicating:

Some required parameters are missing ("posts") for creating the route URL "posts.comments.create".

How can I fix this problem and how can I find out if the solution is applicable for the creation and editing methods in CommentsController?

eg.

  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')); } 
+4
source share
1 answer

I use nested controllers in two projects, I love them. The problem seems to be related to your controller and route reference.

There is no $ post_id in CommentsController. Do something like this:

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

When creating links to a nested controller, the identifier of all ancestors must be specified. In this case, $ post_id is again missing. You may need to make it available for your viewing if it has not already been.

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

Source: https://habr.com/ru/post/1481612/


All Articles