[英]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.