6

I'm trying to send a Axios PATCH request to Laravel 5.6 api. My request contains a FormData.

Laravel's api endpoint doesn't read any of the sent data.

ReactJS code

let data = new FormData();
data.append("photo", this.state.photo);
// append another data ....

const headers = { 
  'Content-Type': 'multipart/form-data',
  'enctype' : 'multipart/form-data',
  'Authorization' : 'Bearer ' + token 
}

axios({
  method : "PATCH",
  baseURL: this.baseURL,
  url    : url,
  params : params,
  data   : data,
  headers: headers,
}).then(response => {
  return response
})

Laravel patch request

public function update(Request $request, $planId)
{
    $data = $request->all();
    dd($data);
}

Laravel request prints an empty array [].

phaberest
  • 3,140
  • 3
  • 32
  • 40
Abeer Elhout
  • 161
  • 1
  • 10
  • 2
    Have you checked what the data sent to the server contains? – Nico Haase Mar 12 '19 at 08:13
  • yes, i use reactjs and redux and i print data after sent it from view to action and print it in the action and it exist but when send it to laravel it doesn't read it – Abeer Elhout Mar 12 '19 at 08:28
  • @AbeerElhout please check in your network tab to make sure the data is sent to the endpoint – phaberest Mar 12 '19 at 08:29
  • 1
    And have you checked through your network console which data is **really** sent? Additionally, try to debug further which data reaches the server - you could use another raw PHP script to simply dump that data – Nico Haase Mar 12 '19 at 08:30
  • @phaberest yes, I did this check and data exist – Abeer Elhout Mar 12 '19 at 08:37

2 Answers2

20

Sad but true, when requesting from the browser it happens that Laravel doesn't properly answer to PATCH or PUT requests.

A quick solution might be using a POST and adding _method: PATCH as post parameter.

Please try with this updated code

let data = new FormData();
data.append("_method", 'PATCH');
data.append("photo", this.state.photo);
// append another data ....

const headers = { 
  'Content-Type': 'multipart/form-data',
  'enctype' : 'multipart/form-data',
  'Authorization' : 'Bearer ' + token 
}

axios({
  method : "POST",
  baseURL: this.baseURL,
  url    : url,
  params : params,
  data   : data,
  headers: headers,
}).then(response => {
  return response
})

Another example of the same issue can be found in axios.patch / axios.put is not working in Vue and Laravel

phaberest
  • 3,140
  • 3
  • 32
  • 40
0

Because HTTP PUT is not recognized by HTML standard.

You need to add POST type of method only but for update you can add a small flag with POST request for a PUT/PATCH type of operation.

axios.post(url, {      // <== use axios.post
 data: data,
 _method: 'patch'      // <== add this field
})
endo64
  • 2,269
  • 2
  • 27
  • 34
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22