【问题标题】:Delete multiple rows using Laravel and Vue Js使用 Laravel 和 Vue Js 删除多行
【发布时间】:2021-04-08 23:26:30
【问题描述】:

在 Laravel 和 Vue Js 中删除多行时遇到问题。我能够将 id 的值作为数组获取。当我单击删除按钮时,我得到状态 200,但没有从数据库中删除任何记录。这是我的代码: 在我的桌子上

 <tr v-for="user in users.data" :key="user.id">
                      <td>{{user.id}}</td>
                      <td>{{user.userName}}</td>
                     <td><input type="checkbox" :value="user.id" v-model="checkedNames"></td>
                       <button class="btn btn-warning" @click=" deleteAllUser()">Delete 
                       Selected</button>
                      </td>
                   </tr>

Vue Js

<script>
    export default {
        data(){
         return{
         checkedNames:[],

功能

deleteAllUser(){
    this.form.post('api/deletehotspotusers/',{id:this.checkedNames}).then(()=>{
                                                                       self.loadHotspotUsers();
                                }).catch(()=> {
                                    Swal.fire("Failed!", "There was something wrong.", "warning");
                                });
                         }
    }

在我的控制器中

public function deleteAll(Request $request){
     if($request->id){
         foreach($request->id as $id){
            HotspotUsers::destroy($id);
         }
     }

我的路线

Route::post('/deletehotspotusers', 'HotspotUsersController@deleteAll');

【问题讨论】:

  • 像这样替换你的 api url ...... this.form.post('/api/deletehotspotusers/',{id:this.checkedNames})......你忘了添加'/' 在你的 url 开头......如果你仍然有同样的问题,那么检查你在你的请求中得到了什么......并且还尝试在你的控制器函数中捕获并 dd($e) 你的异常留言

标签: laravel vue.js axios laravel-vue


【解决方案1】:

要删除模型记录,您需要调用delete 方法。您可以在控制器方法中尝试以下操作

//import use statement at the top of the class
//use Illuminate\Support\Arr;
public function deleteAll(Request $request){
    if($request->id){
        HotspotUsers::whereIn('id', Arr::wrap($request->id))->delete();
    }
}

在Vue中,输入类型checkbox,v-model使用checked属性和change事件,所以v-model会根据checked状态记录true或者false。为了使用 user.id 填充 id,您需要使用更改事件

<tr v-for="user in users.data" :key="user.id">
    <td>{{user.id}}</td>
    <td>{{user.userName}}</td>
    <td>
        <input type="checkbox" :value="user.id" @change="onChecked(user.id)"> 
    </td>
    <td>
        <button class="btn btn-warning" @click=" deleteAllUser()">
            Delete Selected
        </button>
    </td>
</tr>

在方法中的脚本部分

onChecked(id){
    if(!this.names.includes(id)){
       this.names.push(id)
    } else {
        this.names.splice(this.names.indexOf(id),1)
    }
}

【讨论】:

  • 谢谢,但在我的前端是一样的,它显示成功但没有被删除
【解决方案2】:

我不喜欢 vue.js。 如果你的前端运行良好,那么这里是 laravel 代码。 确保 $request->id 正在接收您期望的值。 你可以使用喜欢

Model::destroy([array of primary keys])

如果您的模型的主键是 id,那么您可以指定 id 数组,例如 [1,2,3,4]。 但在使用 logger($request->id) 确保输入值之前。 谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2019-06-24
    • 2021-10-04
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多