compact():未定义的变量:getChoices

时间:2019-09-11 20:39:20

标签: laravel

这是我有这段代码的想法:

$question_one = Questions::orderBy('publish_time', 'desc')->first();
 if (!empty($question_one)) {
   $getChoices =  question_choices::where('questions_id', '=', $question_one->id)->get();
 }

 return view('mySite.after_login', compact('getChoices','question_one'));

当表Questions不为空时,代码将运行并且一切正常,但是当我从表Questions中删除所有查询时,突然向我显示此错误:

  

compact():未定义的变量:getChoices

因此,我需要说的是,如果没有,不要通过它,或者您建议我提出任何好的解决方案:(

2 个答案:

答案 0 :(得分:1)

这是PHP 7.3中使用compact()方法引入的重大更改。它不再将未初始化的变量接受到方法中。要解决此问题,请在发送到压缩之前初始化变量。像这样:

$getChoices = null;  // <-- Just init the variable to null before the if-check
$question_one = Questions::orderBy('publish_time', 'desc')->first();
if (!empty($question_one)) {
    $getChoices =  question_choices::where('questions_id', '=', $question_one->id)->get();
 }

return view('mySite.after_login', compact('getChoices','question_one'));

答案 1 :(得分:0)

$getChoices在if语句中声明。只要if条件为假,它将抱怨未定义的变量。 您可以在if语句上方将其声明为null

$getChoices = null;