I'm trying to create post page with comments; however, it's not working when I add the comment to a post because the system doesn't recognize the post id. What I'm I doing wrong that it doesn't know that the post_id is equal to $post_id
I'm getting the following error:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into
comments
(body
,updated_at
,created_at
) values (This is a test comment, 2017-08-15 19:51:47, 2017-08-15 19:51:47))
COMMENTS FORM
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" method="post" action="{{ $post->id }}/comments">
{{ csrf_field() }}
<div class="form-group">
<textarea name="body" class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
ROUTE
Route::post('/posts/{post}/comments', 'CommentController@store');
CONTROLLER
public function store(Post $post)
{
$post->addComment(request('body'));
return back();
}
COMMENT MODEL
class Comment extends Model
{
protected $fillable = ['body'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
POST MODEL
class Post extends Model
{
public function addComment($body)
{
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}