0

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.

3 Answers 3

1

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'));
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this and i was still getting the same undefined error.
0

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

7 Comments

I tried this too and it didn't work, i tried accessing the value form the view with Session::get('quiz') but the value always came up as NULL.
Hmm that's weird. Does return View::make('quiz.set-questions')->with('quiz', 'test'); show NULL as well?
Nope with 'test' works but when i try passing the array it comes up as NULL.
And what if you use a "sample" array? like $quiz = array('id' => 1, 'totalQuizScore' => 100);
However i just tried "return View::make('quiz.set-questions')->withQuiz($quiz);" and that worked fine thank you, is there any reason why that worked and the others did not? I would like to know for future reference. :)
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.