Laravel - ,无法使用Fetch Api更新多条记录

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

我想更新我的多条记录。但只有第一个记录正在更新,其他记录不是..

我正在使用fetch api进行ajax调用,但我问题不在这里,因为我能够发送数组数据,我可以在浏览器开发部分看到。 (我的意思是,我可以发送多个id数据,没关系)

然后我试图将它们保存在foreach循环中,但只有第一条记录在此循环中更新。

在控制器中

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
            }
    return response()->json("successful");
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }

ajax电话;

ajax.put('comments/approve',token,ids)
      .then(data => data.json())
      .then(log => console.log(log))
      .catch(err => console.log(err))

把方法放在ajax类中

 async put(url, token, data) {

        const response = await fetch(url, {
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": token
            },
            method: "put",
            credentials: "same-origin",
            body: JSON.stringify(data)
        });
        return response;
    }
javascript ajax laravel fetch
1个回答
0
投票

我发现了问题;

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
   //  return response()->json("successful"); (it was here)
            }
    return response()->json("successful"); (it should be in here, not in loop)
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }
© www.soinside.com 2019 - 2024. All rights reserved.