FrancescoMussi
FrancescoMussi

Reputation: 21610

Laravel 4: create comment for a specific post

I am making a simple blog with posts and comments. The resource Comments is a nested resource of Posts. This is the route:

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

Until now i manage all the Post crud and seeing all the comments belonging to a post.

But i don't know how can i create a comment for a post.

In my CommentsController i have the RESTful method create:

class CommentsController extends BaseController {

  protected $comment;


public function __construct(Comment $comment)
{
     $this->comment = $comment;
 }

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

And this is my View create for Comments:

@extends('master')

@section('blog')

<div class="span12 well">
  <h4>Make a Comment</h4>
</div>
<div class="span12 well">

  {{ Form::open(array('route' => 'comments.store')) }}

  {{ Form::close() }}
</div>
@stop

But it doesn't work. I get this error:

Unable to generate a URL for the named route "comments.store" as such route does not exist.

I try also to make('route' => 'posts.comments.store')) and i get this error:

Some mandatory parameters are missing ("posts") to generate a URL for route "posts.comments.store".

Can someone help me please?

EDIT: THis is my Comment Model:

class Comment extends Eloquent 
{
    protected $guarded = array();

    public function post()
    {
        return $this->belongs_to('Post');
    }
}

and this is my Post Model:

class Post extends Eloquent
{
    protected $guarded = array();
    public static $rules = array(
        'title' => 'required',
        'body' => 'required');

    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

Upvotes: 1

Views: 4377

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Having

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

You have 2 store route options:

posts.store

and

posts.comments.store

But not

comments.store

EDIT:

If you take a look at your routes (execute php artisan routes) you'll see that the route to posts.comments.store is:

GET /posts/{posts}/comments/create

So, for this route to work you need to pass the Post id when creating an url to that particular route. This is how you do it in Form::open():

{{ Form::open(array('route' => array('posts.comments.store', $post_id))) }}

And you also need to tweak your controller to make it pass the post Id to your view:

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

Upvotes: 1

Related Questions