K
K
Karpkarp2020-02-07 22:13:35
Laravel
Karpkarp, 2020-02-07 22:13:35

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

2 answer(s)
D
Daniel Marchenkov, 2020-02-09
@Karpkarp

https://laravel.com/docs/6.x/eloquent-relationship...
Adding a relationship to App\Post:

public function comments()
   {
        return $this->hasMany('App\Comment');
   }

And we make the store method like this:
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', 'Комментарий добавлен');
    }

E
Eugene, 2020-02-08
@Nc_Soft

Your url to add a comment should have a post id,
for example POST /comments/15

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question