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 插入为 http://localhost/digitalinvigilator/question?subject=1
但我每次都为空。
谁能帮忙?
- question?subject=1 绝对是不正确的网址。你的网址应该是 question1
- 它是一个可选参数,所以我这样做了。
- 可选参数表示 url 可以是 question 或 question1 或 question12。
- 尝试 Route::get(question/{:subject?}/{sbj_type?}, QuestionController@index)->name(question.index);
- 哦! question?subject=1 有什么办法吗
- 您可以使用 $request 轻松完成此操作
用 $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(); } } } |
- 我没有发送请求的表格,你能详细说明你为什么使用请求吗?
- 您可以通过 get 和 post 方法在任何方法上使用 $request 只需试试这个家伙,让我知道
要按照您指定的方式使用它,您必须在 Request 对象上使用 query 方法。
如果您检查 $subject 是否为假值,您的第一个 if 中也有一个错误。因此,如果 !$subject 为真,它将继续,因此您的 dd($subject) 将始终输出 null 或假值。所以像这样使用它:
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
我猜你已经使用 Request 来访问查询参数了。
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(); } } } |
条件可以根据您在 If
中的要求而有所不同
- 我没有发送请求的表格,你能详细说明你为什么使用请求吗?
- 如果你不使用表单也没关系,查询参数可以通过 Request 访问。如果您不想使用 Request 发送 subject 数据作为 Route Parameter
来源:https://www.codenong.com/54397528/