twoam
twoam

Reputation: 892

Send user id and post id with comment

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.

Upvotes: 3

Views: 1496

Answers (2)

Maraboc
Maraboc

Reputation: 11083

Update your addComment method :

public function addComment($body)
{
    $user_id = Auth::user()->id;
    $this->comments()->create(compact('body', 'user_id'));
}

PS : Assuming that the user is authenticated.

UPDATE

public function addComment($body)
{
    $comment = new Comment;
    $comment->fill(compact('body'));
    $this->comments()->save($comment);
}

Create a new instance of the comment without savingit and you only need to save a comment in the post because a post already belongs to a user

Upvotes: 1

Ali
Ali

Reputation: 3666

There is no need to handle ids manually, let eloquent handle it for you:

$user = Auth::user(); // or $request->user()
$user->comments()->save(new Comment());

more information about saving eloquent models.

Upvotes: 0

Related Questions