0
votes

I am trying to create a comment system for posts on a blog. I created a form for uploading a comment. Both the user_id and the post_id columns are properly populated in the table, however, the body column is empty when enter text and submit it. I defined a relationship that one Post hasMany Comments. Also, I defined that one User hasMany Comments. Here is my code:

//commentcontroller.php

public function newComment(){

        $id=Auth::id();

        $comment = New Comment();

        $comment->user_id=$id;
        $comment->post_id=Input::get('post_id');
        $comment->body=Input::get('body');

        post->comments()->save($comment);
}

Form:

<div class="col-md-8 col-md-offset-2">

<hr>

@foreach($posts as $post)
    <h3>{{ $post->title}}</h3>
    <p>by {{ $post->user->name }}</p>
    <img src='{{ asset($post->image_path) }}' class="img-responsive" id="blogpic"/>
    <p>{{ Str::words($post->body) }}</p>
    <p><a href="{{ action('BlogController@show', $post->id) }}">Read More...</a></p>

    <hr>
            //COMMENT AREA
    {{ Form::open(array('action' => 'CommentController@newComment', 'files'=>true)) }}
            {{ Form::textarea('body', null, array('class'=>'form-control')) }}
    {{ Form::hidden('post_id', $post->id) }}

    <br>

    <br>


    {{ Form::submit('Post') }}

@endforeach

 </div>

I am not concerned yet about displaying comments, just uploading them to the database. The user_id and post_id upload correctly in the database, the text just doesn't save. Thanks in advance.

1

1 Answers

2
votes

You may try this:

public function newComment()
{
    $comment = New Comment();
    $comment->user_id = Auth::user()->id;
    $comment->post_id = $post_id = Input::get('post_id');
    $comment->body = Input::get('body');

    Post::find($post_id)->comments()->save($comment);
}

Notice Auth::user()->id is used instead of Auth::id().