php Laravel雄辩按ID删除

68de4m5k  于 2023-01-29  发布在  PHP
关注(0)|答案(4)|浏览(137)

我尝试按id删除一条记录,但实际上它删除了该表中的所有记录。
下面是我的代码:

    • 查看**
<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>
    • 路线**
Route::post('/status/{statusId}/delete', [
    'uses' => '\Dashboard\Http\Controllers\StatusController@deleteStatus',
    'as' => 'status.delete',
    'middleware' => ['auth'],
]);
    • 主计长**
public function deleteStatus(Request $request, $statusId)
{
    Auth::user()->statuses()->delete($statusId);

    return redirect()->route('home')->with('success', 'Post deleted.');
}
    • 注意:**当我dd($statusId)时,它确实为我正在删除的状态提供了正确的ID。因此,该部分确实有效。
gcuhipw9

gcuhipw91#

这在Laravel 5.6中可以使用destroy方法实现:
来自文档:
但是,如果您知道模型的主键,您可以删除模型而不检索它。

App\Model::destroy(1);

或删除ID数组:

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

或通过查询:

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

ca1c2owp2#

不幸的是,Eloquent构建器不支持将id传递给delete
相反,你必须先找到模型,然后在它上面调用delete

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

c90pui9n3#

您可以使用另一种方法删除模型,如

App\Models\ModelName::find(id)->delete()

但是它抛出了nullPointerException,你必须处理

hts6caw3

hts6caw34#

**Step 1 create route inside web.php**

Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');

 **Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
    {
        $ans = Answer::find($id);
        $ans->delete();
        session()->flash('success', 'Answer Deleted Successfully!!!');
        return view('admin.anser.index');
    }

**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*

<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
  @csrf
  @method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>

相关问题