Answer the question
In order to leave comments, you need to log in
How to get the id of a Laravel post?
Hello.
I can’t figure out how to add comments to specific posts in Laravel.
Created a comments table with the following fields:
comment_id - id of the comment
author_id - id of the pepper that comments
post_id - id of the post that comments
comment - the comment itself
This is the method
public function store(Request $request)
{
$comment = new Comment();
$comment->comment = $request->comment;
$comment->author_id = \Auth::user()->id;
$comment->post_id = Post::get($post_id); <- Вот как тут правильно написать?
$comment->save();
return redirect()->back()->with('success', 'Комментарий добавлен');
}
Answer the question
In order to leave comments, you need to log in
https://laravel.com/docs/6.x/eloquent-relationship...
Adding a relationship to App\Post:
public function comments()
{
return $this->hasMany('App\Comment');
}
public function store(Request $request)
{
$post = Post::findOrFail($request->post_id);
$post->comments()->create([
'author_id' => \Auth::user()->id,
'comment' => $request->comment
]);
return redirect()->back()->with('success', 'Комментарий добавлен');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question