Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios.patch / axios.put is not working in Vue and Laravel

I have this code in my vue file

saveProfile() {
    axios.patch('/api/pegawai/' + this.id, {
         data: this.data
    })
    .then(function (response) {
         console.log(response);
    })
    .catch(function (error) {
         console.log(error);            
    });
}

and in my laravel controller

public function update(Request $request, $id){
     return $this->sendResponse('request retrieved');
}

public function sendResponse($message){
    $response = [
        'success' => true,
        'message' => $message,
    ];
    return response()->json($response, 200);
}

when i run the vue file to pass the data to the controller it should give me a json response to the browser console with the following value

{
  'success' : true,
  'message' : 'request retrieved'
}

but currently it gives me an error 500 internal server error through the browser console. I get the same result if I replace axios.patch with axios.put.

--- What I Have Tried ---

I have tried to do axios.post and axios.get with the same scenarios as axios.patch and both working properly. Controller for post and get:

public function store(Request $request){
    return $this->sendResponse('request retrieved');
}

public function index(){  
    return $this->sendResponse('request retrieved');
}
like image 498
Rafid Avatar asked Jul 04 '18 09:07

Rafid


People also ask

Does Axios work with Vue?

js Axios. Vue. js Axios is defined as an HTTP client request for the node and the browser. Axios can be done with simple JavaScript or React and Vue.

How do I apply an Axios patch?

To perform a PATCH request in Axios you can make use of the "patch" method available from the "axios" object. Do note that this library is a promised-based library so it supports the async/await syntax. Do note that we are using a fake API for testing and the external API is below.

Can I use Axios in laravel?

Just follow the following steps and make Axios HTTP get request in laravel with vue js and pass data blade views or controller to vue component laravel: Step 1: Download Laravel Fresh Setup. Step 2: Setup Database Credentials. Step 3: Generate Fake Data.


1 Answers

actually HTTP PUT is not recognized by html standard. try to do hack like so:

saveProfile() {
    axios.post('/api/pegawai/' + this.id, { // <== use axios.post
         data: this.data,
         _method: 'patch'                   // <== add this field
    })
    .then(function (response) {
         console.log(response);
    })
    .catch(function (error) {
         console.log(error);            
    });
}
like image 64
Hassanal Shah Avatar answered Sep 22 '22 19:09

Hassanal Shah