Laravel调用Firebase实时数据库时遇Undefined variable $collection及语法错误
问题修复:Laravel从Firebase实时数据库取数据到Notification页面的错误解决
错误1:Undefined variable $collection
问题原因
控制器NavBar的notif方法存在两处问题:
- 变量传递不匹配:定义了
$collection变量,但通过compact('push_notif')传递的是不存在的$push_notif,而视图中引用的是$collection - Firebase数据获取不完整:仅调用
getReference()只是获取数据库节点引用,并未实际拉取数据,需要调用getValue()方法获取数据内容
修复后的控制器代码
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Kreait\Firebase\Database; class NavBar extends Controller { public function __construct(Database $database){ $this->database = $database; $this->tablename = 'push_notif'; } // 其他方法保持不变 public function notif(){ // 获取Firebase节点的实际数据 $collection = $this->database->getReference($this->tablename)->getValue(); // 将正确的变量传递到视图 return view('notification', compact('collection')); } // 其他方法保持不变 }
错误2:unexpected token语法错误
问题原因
Blade视图中有两处多余的逗号,导致前端解析时出现语法错误:
<img>标签中src属性闭合后多余的逗号<form>标签中action属性闭合后多余的逗号
修复后的视图关键代码片段
修复img标签
原错误代码:
<img src="{{ asset('build/img/vectors/bin.png?h=79a6fc27e815e003168433b9f14f48ce')}}", width="17" height="17">
修复后:
<img src="{{ asset('build/img/vectors/bin.png?h=79a6fc27e815e003168433b9f14f48ce')}}" width="17" height="17">
修复form标签
原错误代码:
<form action="{{ url('push')}}", method="POST" style="margin-right: 308px;width: 782.2px;min-width: -24px;">
修复后:
<form action="{{ url('push')}}" method="POST" style="margin-right: 308px;width: 782.2px;min-width: -24px;">
内容的提问来源于stack exchange,提问作者Overley Loley
相关产品推荐
相关产品推荐

