简体   繁体   中英

Delete Method in Axios, Laravel and VueJS

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\UsersController@destroy

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!

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}', 'UserController@destroy');
// 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', 'UserController@deleteMany');

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.

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"

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

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}', 'UserController@destroy'); 

//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); 
}
axios.post('/myentity/839', {
  _method: 'DELETE'
})
.then( response => {
   //handle success
})
.catch( error => {
   //handle failure
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM