LoginSignup
1
0

More than 1 year has passed since last update.

[Laravel]firestoreのデータ取得

Posted at

TL; DR

  • firestoreのデータの取得はdocumentからsnapshot へのアクセスが必要
  • snapshotからはdataにアクセスすればデータ取得可能

PHP環境でfirestoreへアクセスしようとした話。

firestoreのデータ内容

image.png

やったこと

記事の通り、サービス化する前に動作確認のためにいったん以下のソースコードが動くか確認

<?php
class FirebaseController extends Controller
{
    protected $db;

    public function __construct()
    {
        $this->db = app('firebase.firestore')->database();
    }

    public function load() {
        $collection = $this->db->collection('talk_api');

        $document = $collection->document('R4166zsxknrklBy607jH');

        return response()->json([
            'data' => $data,
        ]);
    }
}

想定した戻り値

array:1 [▼
    "doc" => "hogehoge"
  ]

とか

{doc: "hogehoge"}

のKey-Value形式のデータ

実際の戻り値

image.png
おや。。。違う。。。

解決策

想定した値を取得するにはsnapshotまでアクセスする必要があった

use Google\Cloud\Firestore\FirestoreClient;

$firestore = new FirestoreClient();
$document = $firestore->document('users/john');
$snapshot = $document->snapshot();

$snapshotにはGoogle\Cloud\Firestore\DocumentSnapshotオブジェクトが格納されており、上記ドキュメントのメソッドたちが使えるようになる

dd($snapshot)すると、

image.png

dataに求めているデータがいる

そして、ドキュメント見ていたらdata()ってメソッドがあったので使ってみたら取得できた

class FirebaseController extends Controller
{
    protected $db;

    public function __construct()
    {
        $this->db = app('firebase.firestore')->database();
    }

    public function load() {
        $collection = $this->db->collection('talk_api');

        $document = $collection->document('R4166zsxknrklBy607jH');
        $snapshot = $document->snapshot();
        $data = $snapshot->data();
        return response()->json([
            'data' => $data,
        ]);
    }
}

所感

当初のソースコードが間違っていただけだった。
いろんな記事を漁っているうちにおかしなソースコード書いているだけだった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0