如何更新数据库中的现有条目?

How do I update an existing entry in my database?

如何正确更新我的数据库?我想修改一个我有 ID 的条目,但返回了 'net::ERR_EMPTY_RESPONSE'。下面是我的控制器:

public function update(Request $request, $id)
    {
        $booking = Booking::query($id);
        $booking->start_date = $request->start;
        $booking->end_date = $request->end;
        $booking->save();
        return response()->json($booking);
    }

这些都是我家定义的blade查看:

      const eventData = {
        id: eventid,
        start: arg.event.start.toISOString(),
        end: arg.event.end.toISOString(),
      };

如何正确更新数据库中的 start_date 和 end_date?

此外,这是我的 Javascript 用于获取:

      const eventid = arg.event.id;
      const eventData = {
        start: arg.event.start.toISOString(),
        end: arg.event.end.toISOString(),
      };
      const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
      console.log(csrfToken);
      fetch(`/api/event/update/${eventid}`, {
        method: 'PUT',
        headers: {
          "X-CSRF-Token": csrfToken
        },
        body: encodeFormData(eventData),
      })
      .then(response => console.log(response))
      .catch(error => console.log(error));
      console.log("Complete");

我不确定您是如何传递预订 ID 的,但根据我在上面看到的,ID 是在请求​​中传递的。试试这个:

public function update(Request $request)
    {
        $booking = Booking::findOrFail($request->id);
        $booking->start_date = $request->start;
        $booking->end_date = $request->end;
        $booking->save();

        return response()->json($booking);
    }

更新记录非常简单,您所要做的就是

public function update(Request $request)
    {
// find the record by it's ID and also update it on the fly if you don't need to process anything else
     $updatedData = Booking::findOrFail($request->id)->update(['start_date' => $request->start, 'end_date' => $request->end]);

     return response()->json($updatedData);
    }