'Updating Database, PUT 405 Method not allowed error

I am trying to update my database via a PUT method:

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

The specific error is `PUT HTTP://localhost:8000/api/event/update/105 405 (Method not allowed). I have tried other methods but they all return similar errors. Additionally here is my Controller code:

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

Route:

Route::post('/event/update/{eventid}', [CalendarController::class, 'update']);

Is this an issue with using 'post' in my route?



Solution 1:[1]

The best way to know that your variables return what you expect them to return is to test as you code.

From my experience, I find that when I dd() variables at every point I declare and instantiate a variable, especially those passed to a function, it saves me a lot of headache.

Change your update method needs to change from:

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

To:

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nelson Ekpenyong