0
votes

i get this error when i want add comment on my posts after relationship

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'Posts_ID' cannot be null (SQL: insert into Comment (Comment, posts_id, updated_at, created_at) values (dwa, , 2018-02-03 16:47:58, 2018-02-03 16:47:58))

Route :

Route::get('/showpost/{showpost}/create/comment', function($ID) {
    $showpost = Posts::find($ID);
    return view('createcomment', compact('showpost'));
});

Route::post('/showpost/{showpost}/create/comment', 'PostController@storecm');

Controller :

public function storecm(Posts $showpost, Request $request)
{
    $showpost->Comment()->create($request->all());
}

View :

<form action="{{ action('PostController@storecm', $showpost->ID) }}" method="post">

    {!! csrf_field() !!}
    <label>Comment :</label>
    <input type="text" name="Comment" id="Comment">
    <button type="submit" class="btn btn-success">Add Comment</button>

</form>
4
A couple of questions: 1) do you have a comment() relationship set up in your Posts model? 2) If you don't, add one. If you do, then you probably need to specify the foreign key as posts_id (plural) since by default it'll be assuming post_id (singular). Also, you may want to look at MVC naming conventions. For example, model class names are typically singular (they represent an instance of the thing). If you follow these, then your relationships will be more likely to work without modifications. (laravel.com/docs/5.5/eloquent#eloquent-model-conventions)tptcat

4 Answers

0
votes

You are getting error in create comment because $request->all() not contain posts_id field ,Do below changes in your Controller :

public function storecm(Posts $showpost, Request $request)
{
   $comment=new Comment();
   $comment->Comment=$request->input('Comment');
   $comment->posts_id=$showpost->ID;
   $comment->save();
}
0
votes

Please check your Comment model that post_id is can be change?

Private $fillable =[
                     ‘post_id’,
                      …..
                    ];

You can use

$comment = $request->all();
$post->comments()->save($comment);
0
votes

remember that use 3 parameteres when use hasMany or hasOne when getting this error

    return $this->hasMany('App\Comment', 'Posts_ID', 'ID');

like this...

0
votes

Make sure that the "posts_id" is present in your MODEL under the fillable section

E.g

protected $fillable = [‘post_id’,'xyz',....];