【问题标题】:Passing $id from href to controller for deleting the row laravel 8 [duplicate]将 $id 从 href 传递给控制器​​以删除行 laravel 8 [重复]
【发布时间】:2021-03-05 15:24:48
【问题描述】:

我正在尝试将 id 传递给控制器​​中的函数以删除该行,但我收到错误代码:

函数 0 传递的参数太少,需要 1 个

这是我的html代码:

<a href="{{ route('undo', $id) }}">Undo</a>

这是我的路线:

Route::get('/admin', [ProductController::class, 'deleteProduct']) -> name('undo');

这是我的控制器代码:

function deleteProduct($id) {

        DB::table('products') -> where('id', '=', $id) -> delete();

        return view('auth.admin');
}

【问题讨论】:

  • 我不这么认为,我试图通过链接而不是表单传递它......也许我没有看到它。
  • 我猜Route::get('/admin', [ProductController::class, 'deleteProduct']) -&gt; name('undo'); 应该改为Route::get('/admin/{id}', [ProductController::class, 'deleteProduct']) -&gt; name('undo');

标签: php laravel eloquent


【解决方案1】:

您没有在路由中定义id

Route::get('/admin/{id}', [ProductController::class, 'deleteProduct']) -> name('undo');

这样route 调用将知道将id 放在哪里并将其发送到函数。

另一种方法是保留路由,但从控制器函数定义中删除 $id,并添加 Request $request 以使 laravel 对象成为请求对象。比在函数内部从请求对象访问$id

$id = $request->input('id');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 2019-03-06
    • 1970-01-01
    • 2018-05-31
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多