发送用户ID和帖子ID以及评论

时间:2017-07-21 14:41:12

标签: php laravel

我正在按照laravel教程创建一个表单,用user_id在帖子上创建评论。我似乎无法理解我如何传递user_id。

Post模型

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);
  }
}

Comment模型

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

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

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

User模型

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();
    }
}

如您所见,我在->addComment模型中调用Post来添加评论。它工作得很好,直到我将user_id添加到Comments表。存储用户ID的最佳方法是什么?我无法让它发挥作用。

2 个答案:

答案 0 :(得分:1)

更新您的addComment方法:

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

PS:假设用户已通过身份验证。

<强>更新

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

在没有保存的情况下创建评论的新实例,您只需要在帖子中保存评论,因为帖子已经属于用户

答案 1 :(得分:0)

无需手动处理ID,让您雄辩地为您处理:

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

more information about saving eloquent models.