Its gonna save it if I hard code article_id, but that's not i want ofc....
Jul 2, 2020
6
Level 3
General error: 1364 Field 'article_id' doesn't have a default value
So what im trying to do is to save reply on article. After a lot of error i think i got to the final one. Basically im not sure how to pass article_id to data.
Controller
public function store(Request $request)
{
request()->validate(['body' => 'required']);
Comment::create([
'user_id' => auth()->id(),
'body' => request('body'),
]);
return redirect('/articles');
}
route
Route::resource('articles.comments', 'CommentController');
or
// Route::post('articles/{article}/comments', 'CommentController@store');
view
<form class="comment-form" method="POST" action="/articles/{article}/comments">
@csrf
<textarea rows="18" cols="6" name="body" placeholder="Messages"></textarea>
<input type="submit" value="Submit">
</form><!-- .comment-form -->
migration
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('article_id')->constrained()->onDelete('cascade');
$table->text('body');
$table->timestamps();
});
Level 29
You need to declare the relationships, after that In model
public function comments(){
return $this->hasMany(Comment::class,article_id);
}
In your controller
$article->comments()->create([
'user_id' => auth()->id(),
'body' => request('body'),
]);
Edit: Refer to this https://laravel.com/docs/7.x/eloquent-relationships#one-to-many
Please or to participate in this conversation.