Send user id and post id with comment

Viewed 1266

I am following a laravel tutorial and created a form to create a comment on a post with the user_id. I can't seem to understand how I pass the user_id.

Post Model

class Post extends Model
{
  protected $guarded = [];

  public function comments()
  {
    return $this->hasMany(Comment::class);
  }

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

  public function user()
  {
    return $this->belongsTo(User::class);
  }
}

CommentModel

class Comment extends Model
{
    protected $guarded = [];

    public function post()
    {
      $this->belongsTo(Post::class);
    }

    public function user()
    {
      $this->belongsTo(User::class);
    }
}

User Model

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
      return $this->hasMany(Post::class);
    }

    public function comments()
    {
      return $this->hasMany(Comment::class);
    }

    public function publish(Post $post)
    {
      $this->posts()->save($post);
    }

}

CommentsController.php

class CommentsController extends Controller
{
    public function store(Post $post)
    {
      $this->validate(request(), ['body' => 'required|min:2']);

      $post->addComment(request('body'));

      return back();
    }
}

As you can see I call ->addComment in the Post Model to add the comment. It worked fine untill I added user_id to the Comments table. What is the best way to store the user id? I can't get it to work.

2 Answers
Related