php - Request input laravel ajax return null on update method

669

I try to update data in laravel with ajax withput method, when I echo request input the result is null, this is my ajax

let formData = new FormData();
formData.append('name', 'lorem ipsum'); // I want get this

$.ajax({
   url     : 'product/17',
   method  : 'put',
   data: formData,
   contentType: false,
   processData: false,
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   },
   success : function(res){
      alert(res); // result is null
   }
});

Route :

Route::resource('/product', 'ProductController');

Controller :

public function update(Request $request, $id){
   echo $id; // result is 17
   echo $request->input('name'); // result is null :(
}

I have been search and try other code but not work, how to solve it? thanks

547

Answer

Solution:

I think may be it's because of method of request. There is different way of sending put request than normal get/post request. You can modify like this:

let formData = new FormData();
formData.append('name', 'lorem ipsum'); // I want get this
formData.append('_method', 'put'); // Specify method

$.ajax({
   url     : 'product/17',
   method  : 'post',
   data: formData,
   contentType: false,
   processData: false,
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   },
   success : function(res){
      alert(res); // result is null
   }
});

Now, You can access data with the same approach.

$request->input('name');

I hope you understand.

People are also looking for solutions to the problem: php - Foreach loop in PhpStorm

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.