Laravel Controller Not handling FormData from React Frontend

I am working on a ReactJS frontend and a Laravel backend. My ReactJS frontend sends FormData to a Laravel controller for updating an event. The FormData is correctly populated on the frontend before being sent, and the payload appears correct in the Chrome network tab. I have tried logging the raw data in Laravel, which confirms that the data is received somewhere in the controller. However, the Laravel controller is not populating any data, and it sends an empty object to the database. The controller only updates the database with new values if I hardcode the data in the controller.

I tried the following:

Logging FormData on the frontend: I confirmed that the FormData is correctly populated before being sent.

Checking the network tab in Chrome: The payload appears correct, indicating that the data is being sent from the frontend as expected.

Logging raw data in Laravel: I verified that the data is received in the controller by logging it, which confirms that the FormData is reaching the server.

I expected the Laravel controller to populate the received FormData into the corresponding variables and update the database with these new values. However, instead, the controller is sending an empty value object to the database. The database only updates correctly if I hardcode the values in the controller.

The ReactJS Front end code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> const finishEvent = async () => {
if (!photoAfter) {
alert("Please upload a photo after event completion.");
return;
}
try {
const formData = new FormData();
setFinishBtnIsLoading(true);
formData.append("photos_after", photoAfter);
formData.append("finished", "true");
await axios.patch(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, {
headers: { "Content-Type": "multipart/form-data" },
});
setFinishBtnIsLoading(false);
setIsCompleted(true);
reward();
} catch (error) {
setFinishBtnIsLoading(false);
alert("An error occurred while completing the event. Please try again.");
}
};
</code>
<code> const finishEvent = async () => { if (!photoAfter) { alert("Please upload a photo after event completion."); return; } try { const formData = new FormData(); setFinishBtnIsLoading(true); formData.append("photos_after", photoAfter); formData.append("finished", "true"); await axios.patch(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, { headers: { "Content-Type": "multipart/form-data" }, }); setFinishBtnIsLoading(false); setIsCompleted(true); reward(); } catch (error) { setFinishBtnIsLoading(false); alert("An error occurred while completing the event. Please try again."); } }; </code>
  const finishEvent = async () => {
    if (!photoAfter) {
      alert("Please upload a photo after event completion.");
      return;
    }
  
    try {
      const formData = new FormData();
      setFinishBtnIsLoading(true);
      formData.append("photos_after", photoAfter);
      formData.append("finished", "true");
  
      await axios.patch(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
  
      setFinishBtnIsLoading(false);
      setIsCompleted(true);
      reward();
    } catch (error) {
      setFinishBtnIsLoading(false);
      alert("An error occurred while completing the event. Please try again.");
    }
  };

The finishEvent controller:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public function finishEvent(Request $request, $id)
{
$event = Event::findOrFail($id);
$request->validate([
'photos_after' => 'nullable|file',
'finished' => 'required|boolean',
]);
// Handle photos_after upload
if ($request->hasFile('photos_after')) {
if ($event->photos_after) {
Storage::delete(str_replace('/storage/', 'public/', $event->photos_after));
}
$file = $request->file('photos_after');
$path = $file->store('public/photos');
$photos_after = Storage::url($path);
} else {
$photos_after = $event->photos_after;
}
// Update the event
$event->update([
'photos_after' => $photos_after,
'finished' => $request->finished,
]);
return response()->json(['event' => $event]);
}
</code>
<code>public function finishEvent(Request $request, $id) { $event = Event::findOrFail($id); $request->validate([ 'photos_after' => 'nullable|file', 'finished' => 'required|boolean', ]); // Handle photos_after upload if ($request->hasFile('photos_after')) { if ($event->photos_after) { Storage::delete(str_replace('/storage/', 'public/', $event->photos_after)); } $file = $request->file('photos_after'); $path = $file->store('public/photos'); $photos_after = Storage::url($path); } else { $photos_after = $event->photos_after; } // Update the event $event->update([ 'photos_after' => $photos_after, 'finished' => $request->finished, ]); return response()->json(['event' => $event]); } </code>
public function finishEvent(Request $request, $id)
    {

        $event = Event::findOrFail($id);

        $request->validate([
            'photos_after' => 'nullable|file',
            'finished' => 'required|boolean',
        ]);

        // Handle photos_after upload
        if ($request->hasFile('photos_after')) {
            if ($event->photos_after) {
                Storage::delete(str_replace('/storage/', 'public/', $event->photos_after));
            }

            $file = $request->file('photos_after');
            $path = $file->store('public/photos');
            $photos_after = Storage::url($path);
        } else {
            $photos_after = $event->photos_after;
        }

        // Update the event
        $event->update([
            'photos_after' => $photos_after,
            'finished' => $request->finished,
        ]);

        return response()->json(['event' => $event]);
    }

The API route:

Route::patch('/events/{id}/complete', [EventController::class, 'finishEvent']);

Cors Config:

'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],

New contributor

Souhaiel Karbaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

The Issue was fixed after following the answers in the following thread:

Laravel PATCH Request doesn’t read Axios form data

edited the axios request as post request and added the method to be PATCH in the header:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const response = await axios.post(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, {
headers: {
"Content-Type": "multipart/form-data",
"method" : "PATCH",
},
}
</code>
<code>const response = await axios.post(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, { headers: { "Content-Type": "multipart/form-data", "method" : "PATCH", }, } </code>
const response = await axios.post(`http://127.0.0.1:8000/api/events/${event.id}/complete`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
      "method" : "PATCH",
    },
  }

I also updated the controller and API route to match the new request type

New contributor

Souhaiel Karbaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật