Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send user id and post id with comment

Tags:

php

laravel

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.

like image 960
twoam Avatar asked Dec 05 '25 14:12

twoam


1 Answers

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

like image 82
Maraboc Avatar answered Dec 07 '25 02:12

Maraboc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!