我想将laravel项目与firebase连接起来。 我这样做:
配置config/services.php
'firebase' => [
'api_key' => 'AIzaSyDrioEmJqa6Ir9ocpl0UuA3No', // Only used for JS integration
'auth_domain' => 'bum.firebaseapp.com', // Only used for JS integration
'database_url' => 'https://8c5c.firebaseio.com',
'secret' => '8wjs4WLjJ5hQ4lsCoUXUWiaJ3RIX',
'storage_bucket' => 'STORAGE_BUCKET', // Only used for JS integration
],
我想从firebase DB获取数据,但是当我在thinker上运行此命令时
App\Users::first();
我收到了这个错误
Illuminate \ Database \ QueryException,消息为'SQLSTATE [HY000] [2002]因为目标机器没有联系 e积极拒绝它。 (SQL:select * from
users
limit 1)'
这也是我的用户模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mpociot\Firebase\SyncsWithFirebase;
class Users extends Model
{
use SyncsWithFirebase;
protected $table = 'users';
}
你指导我吗?
答案 0 :(得分:1)
OK! 最后,我使用本教程并修复我的问题
我的控制器
<?php
namespace App\Http\Controllers;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Illuminate\Http\Request;
class FirebaseController extends Controller
{
public function index(){
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/bumpin-d8c5c-firebase-adminsdk-lerig-cb68aaed.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$db = $firebase->getDatabase();
$reference = $db->getReference('users');
$snapshot = $reference->getSnapshot();
$value = $snapshot->getValue();
dd($value);
return view('welcome' , compact('value'));
}
}
在Firebase控制台中,您可以获取.json文件 遵循这条道路:
Project Preview -> Project setting -> service accounts -> firebase admin sdk
将私钥下载为json文件并将其删除
然后将.json文件移动到控制器并在控制器中使用该名称,如我的示例
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/bumpin-d8c5c-firebase-adminsdk-lerig-cb68aaed.json');
我希望这能有所帮助!
答案 1 :(得分:0)
使用PHP SDK这样连接Firebase with Laravel
public function index(){
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/Laraveltesting-6aeda3a963f2.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri('https://laraveltesting-bd2b9.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
$newPost = $database
->getReference('blog/posts')
->push([
'title' => 'Post title',
'body' => 'This should probably be longer.'
]);
//$newPost->getKey(); // => -KVr5eu8gcTv7_AHb-3-
//$newPost->getUri(); // => https://my-project.firebaseio.com/blog/posts/-KVr5eu8gcTv7_AHb-3-
//$newPost->getChild('title')->set('Changed post title');
//$newPost->getValue(); // Fetches the data from the realtime database
//$newPost->remove();
echo"<pre>";
print_r($newPost->getvalue());
}