Mahmud Adam
Mahmud Adam

Reputation: 3579

Deleting from database raises Request failed with status code 405 error

I am attempting to delete items from a MySQL database by id using axios. In my Vue component I have the following method set up to handle removing an item:

deleteTodo(id, index){
        axios.delete('api/todos/' + id).then(function(response){
             console.log(response)
             this.todos.slice(index, 1)
        }.bind(this)).catch((err) => {
              console.log(err)
        })       
}

I am calling deleteTodo in my template like so:

 <li v-for="(todo, index) in todos">
     <span>{{todo.todo}} <button @click="deleteTodo(todo.id, index)">delete</button></span>
 </li>

In my TodoController I have the following method:

 public function remove($id)
 {
    DB::table('todos')->where('id', $id)->delete();
    return redirect('todos');
 }

If I attempt to delete an item, I get the following error in the console:

Error: Request failed with status code 405
Stack trace:
createError@http://localhost:8000/js/app.js line 107 > eval:15:15
settle@http://localhost:8000/js/app.js line 193 > eval:18:12
handleLoad@http://localhost:8000/js/app.js line 86 > eval:77:7

If I refresh the browser, it app items are indeed being deleted (I also can confirm they are being deleted by visiting api/todos route). However, I have to hit the delete button twice and refresh the browser for it to actually delete the item from the database.

Why am I getting this error, and how do I fix it?

Upvotes: 1

Views: 1643

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

The problem most probably comes from HTTP redirect with return redirect('todos'); whereas the request is a JSON/AJAX request (from Vue component using axios), and therefore should return a JSON response. Changing the return statement to return response()->json('Deleted'); should do the trick.

Upvotes: 1

Related Questions