laravel 5.7函数的参数太少

时间:2019-01-28 07:46:58

标签: php laravel laravel-5

我想使用两个可选参数查询数据库,因此我将路由定义为:

web.php

Route::get('question/{subject?}/{sbj_type?}', 'QuestionController@index')->name('question.index');

之后,我在 QuestionController.php 中创建了一个函数,如下所示:

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();
        }
    }
}

此后,我以http://localhost/digitalinvigilator/question?subject=1的形式插入了 URL 但是我每次都变成空。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

尝试使用$ request

在您的Route / Web.php上

Route::get('question', 'QuestionController@index')->name('question.index');

在您的控制器上

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 :(得分:0)

我想您已经使用Request来访问查询参数。

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中的要求,条件可以有所不同

答案 2 :(得分:0)

要像指定的那样使用它,必须在query对象上使用Request方法。

如果您检查$subject是一个伪造的值,那么您的第一个错误也存在。因此,如果!$subject为true,它将继续,因此您的dd($subject)将始终输出null或伪造的值。所以像这样使用它:

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