Laravel Eloquent 按 id 删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32615904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:21:15  来源:igfitidea点击:

Laravel Eloquent delete by id

phplaravel

提问by Sam

I'm trying to delete a single record by id. Instead, it deletes all records in that table.

我正在尝试按 id 删除单个记录。相反,它会删除该表中的所有记录。

Here's my code:

这是我的代码:

View

看法

<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
    <button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
    <input type="hidden" name="_token" value="{{ Session::token() }}">
</form>

Routes

路线

Route::post('/status/{statusId}/delete', [
    'uses' => '\Dashboard\Http\Controllers\StatusController@deleteStatus',
    'as' => 'status.delete',
    'middleware' => ['auth'],
]);

Controller

控制器

public function deleteStatus(Request $request, $statusId)
{
    Auth::user()->statuses()->delete($statusId);

    return redirect()->route('home')->with('success', 'Post deleted.');
}

Note:When I dd($statusId)it does provide the right ID for the status I'm deleting. So that part does work.

注意:当我dd($statusId)确实为我正在删除的状态提供了正确的 ID 时。所以那部分确实有效。

回答by Joseph Silber

Unfortunately, the Eloquent builder does not support passing the id to delete.

不幸的是,Eloquent 构建器不支持将 id 传递给delete.

Instead, you have to first find to model, then call deleteon it:

相反,您必须首先找到模型,然后调用delete它:

$request->user()->statuses()->findOrFail($statusId)->delete();

回答by toing_toing

This is possible in Laravel 5.6 using the destroy method:

这在 Laravel 5.6 中使用 destroy 方法是可能的:

From the docs:

文档

However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the destroy method

但是,如果您知道模型的主键,则可以删除模型而不检索它。为此,请调用 destroy 方法

App\Model::destroy(1);

or to delete an array of ids:

或删除一组 id:

App\Model::destroy([1, 2, 3]);

or by query:

或通过查询:

App\Model::where('active', 0)->delete();