从 Laravel 5.4 数据库中删除一个值

Delete a value from a Laravel 5.4 database

我正在尝试从 Laravel 5.4 中的数据库中删除值。这是我的代码:

UserController.php:

public function destroy($id)
{

 $user = User::find($id);
 $user->delete();
 return redirect()->route('user.index');
}

View.blade.php

<div class="table-responsive">
    <table id="datatable-account"
           class="table table-vcenter table-hover table-condensed table-bordered text-center">
        <thead>
        <tr>
            <th class="text-center">Username</th>
            <th class="text-center">Last Name</th>
            <th class="text-center">First Name</th>
            <th class="text-center">Role</th>
            <th class="text-center">Email</th>
            <th class="text-center">Action</th>
        </tr>
        </thead>
    </table>

</div>

<script type="text/javascript">

$('#datatable-account').DataTable({
    processing: true,
    serverSide: true,
    "ajax": '{!! url('api/user') !!}',
    "columns": [
        {data: 'username', name: 'username'},
        {data: 'lastname', name: 'lastname'},
        {data: 'firstname', name: 'firstname'},
        {data: 'role', name: 'role',
            render: function (data, types, full, meta) {
                if (data == 0){ return 'Admin' } else return 'User';}
        },
        {data: 'email', name: 'email'},
        {data: 'id', name: "id",
            render: function (data, types, full, meta) {
                return '<a href="{{ url('delete')}}" data-method="delete" button type="button" class="btn btn-danger btn-xs delete-user" name="delete"><i class="fa fa-times"></i> Delete</button></a>';
            }
        }
    ]
});

Routes.php

Route::post('/delete', ['as' => 'delete', 'uses' => 'UserController@destroy']);

当我点击删除按钮时,没有出现错误,但数据库中的值仍然存在。我缺少什么。提前致谢。

更新您的 route 以便请求方法为 DELETE 并按照@Rodrane 的建议附加 user_id

Route::delete('/delete/{id}', 'UserController@destroy');

然后在您的 view 中更新删除 link 看起来像这样。

return '<a href="{{ url('delete'.$id)}}" data-method="delete" button type="button" class="btn btn-danger btn-xs delete-user" name="delete"><i class="fa fa-times"></i> Delete</button></a>';

答案已更新 我认为您需要像这样更新您的代码:

Route.php

Route::get('/delete/{id}','UserController@destroy')->name('delete');

View.blade.php 只需更新您删除 link 代码,下面给出:

return '<a href="{{ route('delete', [$id])}}" data-method="delete" button type="button" class="btn btn-danger btn-xs delete-user" name="delete"><i class="fa fa-times"></i> Delete</button></a>';

已解决。我创建了另一个控制器并使用了代码

<form action="{{route('UserController.destroy',$sub->id)}}" method="post">
                        <input type="hidden" name="_method" value="delete">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Se sicuro di voler cancellare il subscriber?');" name="name" value="Elimina">
                    </form>

当 $sub 变量是 table "datatable-account" 中的 foreach 变量时。 非常感谢您的帮助!