簡體   English   中英

laravel 5.7 函數的參數太少

[英]Too few arguments to function laravel 5.7

我想使用兩個可選的參數查詢數據庫,所以我定義了一個路由:

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

之后,我將此URL插入為http://localhost/digitalinvigilator/question?subject=1但每次都為空。

任何人都可以幫忙嗎?

用 $request 試試這個

在你的路線/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();
    }
  }
}

我猜您已經使用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的要求而有所不同

要像您指定的那樣使用它,您必須在Request對象上使用query方法。

如果您檢查$subject是否為假值,那么您的第一個 if 中也有一個錯誤。 因此,如果!$subject為真,它將繼續,因此您的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM