【问题标题】:Laravel Too few arguments to functionLaravel 参数太少而无法运行
【发布时间】:2020-06-06 21:54:01
【问题描述】:

我有一个使用 Laravel 生成一些代码的简单应用程序,现在我正在尝试使用 url 将唯一 id 传递给我的控制器。

这是应该接收 ID 的方法:

 public function code($code_id)
 {
     $settings = Setting::find($code_id);

     return view('pages.settings.code', compact('settings'));
 }

这是我传递 ID 的视图文件:

<a href="{{ route('settings.code', $settings->code_id) }}">
    {{ __('Generate Code') }}
</a>

当我检查我得到的 URL 时:

http://127.0.0.1:8001/settings/code?K1zMXRZG4

这是我的路线:

Route::get('settings/code', [
    'as' => 'settings.code', 
    'uses' => 'SettingController@code'
]);

Route::resource('settings', "SettingController");

但我收到以下错误:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Too few arguments to function App\Http\Controllers\SettingController::code(), 0 passed and exactly 1 expected

我的代码有什么问题?

【问题讨论】:

  • 告诉我们你的settings.code路线
  • 好的,我会建议 KFoobar 在回答中告诉你的内容

标签: php laravel laravel-routing


【解决方案1】:

您需要定义应该传递给路由中的方法的任何参数:

Route::get('/settings/code/{code_id}', 'MyController@code')
    ->name('settings.code');

这会将$code_id 传递给控制器​​中的code() 方法。

如果您没有在路由中定义参数,它将作为Request-object 中的参数传递 - 就像所有查询字符串一样 - 您需要在控制器中像这样获取它:

$code_id = $request->query('code_id');

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2013-06-24
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多