简体   繁体   中英

Laravel : Undefined variable in blade?

In am getting Undefined variable: score (View: C:\\Users\\Sarthak\\blog\\resources\\views\\submitquestion.blade.php) in blade view when executing :

Controller part

public function question(Request $request)
{
    static $startscore = 0;
    $getidvalue = Input::get('getid');
    $getanswervalue = Input::get('getanswer');
    $dbscore = DB::table('5question')->select('question_id', 'correct_answer', 'question_marks')->where('question_id', '=', $getidvalue)->get();
    foreach($dbscore as $value) {
        if ($getanswervalue == ($value->correct_answer)) {
            $getscore = $startscore + $value->question_marks;
        }
        elseif ($getanswervalue == null) {
            $emptyvalue = - 1;
            $getscore = $startscore + $emptyvalue;
        }
        else {
            $novalue = 0;
            $getscore = $startscore + $novalue;
        }
    }

    echo "$getscore";
    Session::push('getscoresession', $getscore);
    $getsession = ['qid' => $getidvalue, 'answer' => $getanswervalue];
    Session::push('answer', $getsession);

    // return response()->json(['qid'=>$getidvalue,'answer'=>$getanswervalue]);

    $score = array_sum(Session::get("getscoresession"));

    // return view('submitquestion',compact('score'));

    return view('submitquestion', ['score' => $score]);
}

Blade part :

You have submitted quiz and your score is : {{ $score }}> LOGOUT

试试这个:

return view('submitquestion', compact('score'));

you can pass variable form controller to view using with and compact :

$request->session()->put('getscoresession', $getscore);
$getsession = ['qid' => $getidvalue, 'answer' => $getanswervalue];
$request->session()->put('answer', $getsession);

if ($request->session()->has('getscoresession')) {
     $score = array_sum($request->session()->get("getscoresession"));
}else{
      $score = 0;
 }

using with :

$score= 10;  
return view('submitquestion')->with('score',$score);

using compact :

return view('submitquestion',compact('score'));

Try it. If you get error from your controller send $score = 10; return view('submitquestion')->with(['score' => $score]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM