Compact():Laravel 8中的未定义变量
我仍然是Laravel的初学者。这次,我收到了一个错误代码,如下以下
消息:错误代码:
errorexception compact():未定义的变量:countanswer
compact():未定义的变量:我的控制器中的
public function home (Request $request) {
...
$arr_spesialis = [];
foreach ($expert_list as $data) {
$countanswer = DB::table('questions')
->where('expert_id', '=', $data->id)
->count();
$data->countanswer = $countanswer;
}
$arr_spesialis = [];
foreach ($expert_popular as $data) {
$countanswerpopular = DB::table('questions')
->where('expert_id', '=', $data->id)
->count();
$data->countanswerpopular = $countanswerpopular;
}
return view('petani.Tanyapakar.TanyapakarListPakar',compact('user', 'expert_list','expertises_list', 'expert_popular', 'subscribe', 'countanswer'));
}
:我该如何处理代码?谢谢。有人可以解释为什么会遇到错误吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
$ countanswer
在 foreach 内。尝试以下操作:说明
当PHP中创建变量时,只能在其创建的范围内使用。在您的情况下,现在变量
$ countanswer
将具有一个值,只要它在循环内部,但是一旦循环停止并控制了控制,该变量就会被破坏,从而使其不确定。用于剩余的函数范围。您还可以明确定义变量的范围,如果您需要在程序中采取此类操作,请阅读更多有关
Your
$countanswer
is insideforeach
which means that it is created and destroyed within the loop causing it to never remain in the complete scope of functionhome
. Try this:Explanation
When a variable is created in PHP it can only be used inside the scope it is created. In your case the foreach, now the variable
$countanswer
will have a value as long as it is inside the loop but as soon as the loop stops and control flow out, the variable will be destroyed making it undefined for remaining scope of the function.You can also define scope of variables explicitly if there's a need of such action inside your program, read more about PHP Variable Scopes