问题
i am new to laravel and i have been following the documentation and several videos but for hours now i have been trying to pass an array from the controller to a view but i keep getting this error in the view:
Undefined variable: quiz
This is the controller code:
public function SetQuestions($id)
{
$query = Quiz::find($id);
$quiz = array(
'id' => $query->id,
'noQuestions' => $query->no_questions,
'totalQuizScore' => $query->total_quiz_score
);
return View::make('quiz.set-questions')->with($quiz);
}
This is the route:
Route::resource("/quiz/set-questions/{id}", 'QuizController@SetQuestions');
This is the code in the view:
<?php var_dump($quiz); ?>
For now i'm just dumping the data to see if the value changes form null.
回答1:
As described in the docs the view method takes two arguments. The first is the name of the variable you want it to be accessible by in the view, the second is the actual data.
return View::make('quiz.set-questions')->with('quiz', $quiz);
There are also a few other options
return View::make('quiz.set-questions')->withQuiz($quiz);
return View::make('quiz.set-questions', array('quiz'=>$quiz));
return View::make('quiz.set-questions', compact($quiz));
All these have the same result
回答2:
Use compact and then just call $quiz
in your view.
public function SetQuestions($id)
{
$query = Quiz::find($id);
$quiz = array(
'id' => $query->id,
'noQuestions' => $query->no_questions,
'totalQuizScore' => $query->total_quiz_score
);
return View::make('quiz.set-questions', compact('quiz'));
}
回答3:
For Laravel 5 you have to do something like this.
Route::get('/', function(){
$people = ['John','Joe','Jack'];
return view('welcome',compact('people');
});
If you pass $people
you will get an error.
来源:https://stackoverflow.com/questions/27071828/unable-to-pass-array-from-controller-to-view-in-laravel