Home > OS >  How do I update an existing entry in my database?
How do I update an existing entry in my database?

Time:03-03

How can I update my database properly? I'd like to modify an entry for which I have the id for, but a 'net::ERR_EMPTY_RESPONSE' is returned. Below I have my Controller:

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

These are all defined in my home blade view:

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

How do I properly update start_date and end_date in my database?

Additionally, this is my Javascript used to fetch:

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

CodePudding user response:

Here you go

documentation link https://laravel.com/docs/8.x/eloquent#updates

   $booking = Booking::findOrFail($id);
   $booking->start_date = $request->start;
   $booking->end_date = $request->end;
   $booking->save();

CodePudding user response:

I'm not sure how you're passing the ID for the booking, but from what I can see on the above, the ID is being passed in the request. Try this:

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

CodePudding user response:

Updating a record is straight forward all you've got to is

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