Too few arguments to function laravel 5.7
我想使用两个可选参数查询数据库,所以我定义了一个路由:
web.php
1 | Route::get('question/{subject?}/{sbj_type?}', 'QuestionController@index')->name('question.index'); |
之后我在 QuestionController.php 中创建了一个函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function index($subject = null, $sbj_type = null) { $questions; if (!$subject) { dd($subject); if (!$sbj_type) { $questions = Question::where(['subject_id' => $subject, 'sbj_type_id' => $sbj_type])->get(); } else { $questions = Question::where(['subject_id' => $subject])->get(); } } } |
之后我将该 URL 插入为
但我每次都为空。
谁能帮忙?
用 $request 试试这个
在你的 Route/Web.php
1 | Route::get('question', 'QuestionController@index')->name('question.index'); |
在你的控制器上
1 2 3 4 5 6 7 8 9 10 11 | public function index(Request $request){ $questions; if ($request->subject) { if (!$request->sbj_type) { $questions = Question::where(['subject_id' => $request->subject, 'sbj_type_id' => $request->sbj_type])->get(); } else { $questions = Question::where(['subject_id' => $request->subject])->get(); } } } |
要按照您指定的方式使用它,您必须在
如果您检查
1 2 3 4 5 6 7 8 9 10 11 12 | public function index(Request $request) { $questions; if ($request->query('subject')) { dd($subject); if ($request->query('sbj_type')) { $questions = Question::where(['subject_id' => $request->query('subject'), 'sbj_type_id' => $request->query('sbj_type')])->get(); } else { $questions = Question::where(['subject_id' => $request->query('subject'))->get(); } } } |
来源:https://laravel.com/docs/5.7/requests#retrieving-input
我猜你已经使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function index(Request $request, $subject = null, $sbj_type = null) { $questions; if (!$request->has('subject)) { dd($subject); if (!$sbj_type) { $questions = Question::where(['subject_id' => $subject, 'sbj_type_id' => $sbj_type])->get(); } else { $questions = Question::where(['subject_id' => $subject])->get(); } } } |
条件可以根据您在
中的要求而有所不同