1
votes

So I have a Posts model that has many comments and belongs to a user, so when I want to add a comment, which belongs to a post and a user, I must give it a user a id, and this is what I tried.

use App\Posts;
use App\Comment;
class CommentsController extends Controller
  {
    public function store(Posts $post)
       {
          $this->validate(request(), ['body' => 'required|min:2']);
          $post->addComment(request([
               'body' => request('body'),
               'user_id' => auth()->user()]));
        }
    } 

But what I am getting is

Type error: Too few arguments to function App\Posts::addComment(), 1 passed 2 expected.

The addcoment method, from the posts model:

public function addComment($body, User $userid)
{
    $this->comments()->create(compact('body', 'userid'));

    return back();

}

Following this tutorial https://laracasts.com/series/laravel-from-scratch-2017/episodes/19, but the tutor skipped this step.

1
show your routing - Pankaj Makwana
I added it to the post. - Daniel Santos
It seems that you are passing a single argument to addComment function while it requires two. request([ 'body' => request('body'), 'user_id' => auth()->user()]) - Basheer Kharoti
Yes, but i wish to give it a user_id, otherwise i will get an error. - Daniel Santos
Where is route? Route::get("/", "CommentControler@addComment") - Pankaj Makwana

1 Answers

1
votes

Your method addComment($body, User $userid) needs 2 arguments!

You should try something like this :

$post->addComment(request('body'),auth()->user());

OR (I'm not sure for this one) This one below will not work.

$post->addComment(request(['body' => request('body')],auth()->user());