Abeer Elhout
Abeer Elhout

Reputation: 161

Laravel PATCH Request doesn't read Axios form data

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 [].

Upvotes: 6

Views: 4820

Answers (2)

NIKUNJ KOTHIYA
NIKUNJ KOTHIYA

Reputation: 2165

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

Upvotes: 0

phaberest
phaberest

Reputation: 3220

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

Upvotes: 20

Related Questions