2017-09-24 77 views
0

我試圖通過愛可信發送刪除請求到laravel如下:刪除方法在愛可信,Laravel和VueJS

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

現在從愛可信文件我讀了刪除請求,我們應該使用一個configObject所以上述可改寫爲這樣:

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

我有那麼Route::resource('users', 'UsersController');在api.php所以刪除默認路由是:

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

和控制器的方法是:

|App\Http\Controllers\[email protected] 

我能當我通過一個ID假設API /用戶/ 12,它被正確地刪除,但刪除預期用戶,當我嘗試通過上面的數組變得複雜。

如果我嘗試按照axios文檔axios.delete('api/users/', {params: {id: this.checkedNames}})它看起來我發送這個http://lorillacrud.dev/api/users?id[]=21&id[]=20但我得到405方法不允許。

如果我嘗試axios.delete('api/users/' + this.checkedNames)我得到http://lorillacrud.dev/api/users/20,21所以在我的銷燬方法,我可以抓住id和刪除,但我想知道這是否是正確的方法嗎?

更新

我好像我做了工作,但我不理解所以還是讚賞做什麼我做實際工作的感覺任何幫助!

因此,如果變化:

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

,並在我的破壞方法:

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

所以......

// 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) 

對不起你們,但我有很多的困惑爲什麼和什麼!

路由名稱爲user.destroy爲什麼當我傳遞一個數組時,它不工作,當我傳遞一個單值時,爲什麼viceversa方法刪除的路由在傳遞數組時不會刪除?

使用api/users/destroyapi/users僅有什麼區別?

感謝您的任何幫助!

+0

感謝您的編輯,下一個問題會更加謹慎。 –

回答

0

這是因爲方法簽名。使用Resource時,默認delete路由需要單個參數。這樣做的時候:

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

你缺少一個需要參數。路由定義是

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

通常,如果您要偏離默認行爲,建議您創建自己的函數。因此,您可以保留默認的destroy($id)函數來刪除單個條目並編寫一個刪除許多條目的新函數。通過添加路由開始爲它

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

然後定義函數來處理它

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

總之,你的問題就來了,從路由定義。您的路線從Axios與Laravel的路線定義不符,因此是405.

+0

好吧,我明白了,非常感謝我正在專注於params,而錯誤是在laravel一邊!感謝您指出了這一點。 –