Delete Method in Axios, Laravel and VueJS

All we need is an easy explanation of the problem, so here it is.

I am trying to send a delete request via axios to laravel as follow:

axios.delete('api/users/' + this.checkedNames)
.then((response) => {
    console.log(response)
}, (error) => {
    // error callback
})

Now from axios documentation I read that for delete request we should be using a configObject so the above could be rewritten as so:

axios.delete('api/users/', {params: {ids:     
    this.checkedNames})
.then((response) => {
    console.log(response)
}, (error) => {
    // error callback
})

I have then Route::resource('users', 'UsersController'); in api.php so the default route for deleting is:

DELETE| api/users/{user}| users.destroy 

and the controller’s method is:

|App\Http\Controllers\[email protected]

I am able to delete as expected a user when I pass a single id let’s say api/users/12, it gets deleted correctly but when I try to pass the array above things get complicated.

if I try as per axios documentation axios.delete('api/users/', {params: {id: this.checkedNames}}) it looks I am sending this http://lorillacrud.dev/api/users?id[]=21&id[]=20 but I get a 405 method not allowed.

if I try axios.delete('api/users/' + this.checkedNames ) I get http://lorillacrud.dev/api/users/20,21 so in my destroy method I could grab the ids and delete, but I am wondering if this is the correct way to do it?

update

I seemed I made it work but I am not understanding so any help still appreciated to make a sense of what I am actually making work!

So, if change to:

axios.delete('api/users/destroy', {params: {'id': this.checkedNames})

and in my destroy method:

    if ($request->id) {
        foreach ($request->id as $id) {
            User::destroy($id);
        }
    }
    User::destroy($id);
}

So…

// not deletes the user
axios.delete('api/users/destroy', {params: {id: id}}) 

// ok deletes the users when using request->id in a for loop in the destroy laravel method.
axios.delete('api/users/destroy', {params: {ids: this.checkedNames}}) 

// ok deletes one user
axios.delete('api/users/' + id)

sorry guys but I have a lot of confusion why and what !!!

The route name is user.destroy why does it work when I pass an array and it does not when I pass a single value, why viceversa the route with method delete will not delete when pass an array ???

Any difference between using api/users/destroy vs api/users only?

Thanks for any help on this!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I also experienced the same problem. This works for me:

deletePost: function(id) {
                axios.post('/posts/'+id,{_method: 'delete'})
            }

Using axios.post() instead of axios.delete, and sending _method “delete”

Method 2

It is because of the method signatures. The default delete route when using Resource expects a single parameter. So when doing:

axios.delete('api/users', {params: {'id': this.checkedNames})

you are missing a required parameter. The route definition is

Route::delete('api/users/{id}', '[email protected]');
// You are missing `id` here. So it won't work. 

Usually, if you are going to stray away from the default behavior, it is recommended to create your own function. So you could leave the default destroy($id) function as is to delete a single entry and write a new function that will delete many. Start by adding a route for it

Route::delete('api/users', '[email protected]');

Then define the function to handle it

public function deleteMany(Request $request)
{
    try 
    {
        User::whereIn('id', $request->id)->delete(); // $request->id MUST be an array
        return response()->json('users deleted');
    }

    catch (Exception $e) {
        return response()->json($e->getMessage(), 500);
    }
}

To summarise, your problem came from route definition. Your route from Axios did not match the route definition from Laravel, hence the 405.

Method 3

I was having issue to send data as model while making delete request. I found a fix as follows:

deleteCall (itemId, jsonModel) {
return api.delete(`/users/${itemId}/accounts/`, {data: jsonModel})
},

Method 4

Deleting users in array

Other good option, is to convert javascript array to string, and pass it has the required parameter, instead of passing object. Here the example:

In Vue.js 2.5.17+

//Use the javascript method JSON.stringify to convert the array into string:
axios.delete('api/users/' + JSON.stringify(this.checkedNames))

In Laravel 5.3+

//Resource default route (you don't need to create, it already exists)
Route::delete('api/users/{id}', '[email protected]'); 

//In laravel delete method, convert the parameter to original array format 
public function destroy($id)
{
    User::destroy(json_decode($id); //converting and deleting users in array 'id'
}

Deleting single user by id

Just pass the id. You don’t need to convert it.

In Vue.js 2.5.17+

axios.delete('api/users/' + id)

In Laravel 5.3+

You can name the parameter as you wish: user, id, item ,…

In Laravel 5.6+ < is named as $id //this can be the id or the user object
In Laravel 5.7+ > is named as $user //this can be the id or the user object

public function destroy($id)
{
    User::destroy($id); 
}

Method 5

axios.post('/myentity/839', {
  _method: 'DELETE'
})
.then( response => {
   //handle success
})
.catch( error => {
   //handle failure
})

https://www.mikehealy.com.au/deleting-with-axios-and-laravel/

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply