Delete Method in Axios, Laravel and VueJS

前端 未结 4 1448
忘掉有多难
忘掉有多难 2021-01-11 16:49

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

axios.delete(\'api/users/\' + this.checkedNames)
.then((response) => {
    console.log         


        
4条回答
  •  旧巷少年郎
    2021-01-11 17:06

    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.

提交回复
热议问题