Laravel中的更新评论

问题描述 投票:0回答:1

我是Laravel的新手,我想在Laravel Controller中使用if语句。所以我有一个表单标记,可以在其中添加注释。我想以相同的形式编辑评论。这是我的表单标签:

<form method="post" action="/hotels/{{$id}}" name="review_hotel">
     @csrf
     <div class="form-group">
         <textarea name="comment" id="comment" class="form-control" style="height:100px"
                   placeholder="Write your review"></textarea>
         @error('comment')
             <p class="text-danger">{{$message}}</p>
         @enderror
     </div>
     <input type="submit" value="Submit" class="btn_1" id="submit-review">
</form>

我有一个脚本,借助此脚本,我可以添加要更改为文本区域的注释。在此之后,我不知道如何在控制器中对其进行更新。这是CommentController:

public function comment(CommentRequest $request, $id)
    {
        $comment = new Comment();
        $comment->object_id = $id;
        $comment->user_id = Auth::id();
        $comment->comment = $request['comment'];
        $comment->save();
        return redirect('/hotels/'.$id);
    }

我认为我需要在控制器中编写“ if”语句,但是我不知道该怎么做。也许有一种更简单的方式来更新评论?

laravel insert-update laravel-6
1个回答
0
投票

在您的模型Comment.php上,将表单变量标记为可填充

public $fillable = ['object_id', 'user_id', 'comment'];

然后使用此Model函数(口才的)

Comment::updateOrCreate(
[
'object_id' => ...,
'user_id' => ...,
],
[
'object_id' => ...,
'user_id' => ...,
'comment' => ...,
]
);

https://laravel.com/docs/5.8/eloquent#other-creation-methods

© www.soinside.com 2019 - 2024. All rights reserved.