I am encountering an issue when sending a PATCH request in my Laravel application. When sending a PATCH request to update a resource, I am not getting the expected result. However, when I send the same request using the POST method, I get the desired result. What could be the issue with the PATCH request?
// web
Route::patch('{id}/update', [UrunlerController::class, 'update'])->name('magaza.urun.guncelle.submit');
// Controller
public function update(Request $request, string $id)
{
$sayi = $request->input('sayi');
return response()->json([
'success' => true,
'sayi' => $sayi
]);
}
// vanilla js
document.getElementById('patates').addEventListener('click', function() {
var formData = new FormData();
formData.append('sayi', 123); // Basit veri ekliyoruz
var url = `{{ route('magaza.urun.guncelle.submit', ['id' => 8]) }}`;
fetch(url, {
method: 'PATCH',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Hata:', error);
});
});
The result I expected
{
"success": true,
"sayi": "123"
}
The result I encountered
{
"success": true,
"sayi": null
}
Laravel v:11.20.0
6
It seems like the issue lies in how the FormData
object is being handled in your JavaScript. When sending a PATCH
request with FormData
, Laravel may not be able to parse it as expected unless you specify the Content-Type
properly or handle the request differently.
Here are a few steps to resolve this:
1. Add _method
to FormData
Since Laravel uses _method
to spoof HTTP verbs like PATCH
when submitting forms, try adding it explicitly to your FormData
object:
formData.append('_method', 'PATCH');
3. Modify Controller for Debugging
To verify that Laravel is receiving the correct data, add some debug logging in your controller to inspect the request data:
public function update(Request $request, string $id)
{
Log::info($request->all()); // Log the request data
$sayi = $request->input('sayi');
return response()->json([
'success' => true,
'sayi' => $sayi
]);
}
2