Search code examples
phplaravelfirebasegoogle-cloud-platformgoogle-cloud-firestore

Fatal Error: Call to undefined method Google\Cloud\Firestore\QuerySnapshot::count()


I want to echo 5000 user's documents from Firerstore to an HTML table using Laravel but am getting an error "call to undefined method Google\Cloud\Firestore\QuerySnapshot::count()". Please what am I getting wrong here:

public function history(Request $request)
    {
        $history = app('firebase.firestore')->database()->collection($this->tablenamePayment);
        $lastVisible = null;
        if ($request->input('last_visible')) {
            $lastVisible = $history->document($request->input('last_visible'))->snapshot();
        }
        $query = $history->startAt($lastVisible ? [$lastVisible] : []);
        $documents = $query->limit(2000)->documents();
        $data = [];
        foreach ($documents as $document) {
            $data[] = [
                 'id' => $document->id(),
                'name' => $document->get('name'),
                'email' => $document->get('email'),
            ];
        }
        $nextVisible = null;
        if ($documents->count() === 2000) {
            $nextVisible = $documents->last()->id();
        }
     return view('admin.payment-history', compact('data', 'nextVisible'));
    }
// View (Blade template):

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach($data as $document)
            <tr>
                <td>{{ $document['id'] }}</td>
                <td>{{ $document['name'] }}</td>
                <td>{{ $document['email'] }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

@if ($nextVisible)
    <a href="{{ route('firestore', ['last_visible' => $nextVisible]) }}">Next Page</a>
@endif

Solution

  • As mentioned by @AlexMamo, you are not handling a laravel collection but an instance of QuerySnapshot. The methods count() & last() dont exist on that class (or are defined with a different name, for example instead of count() you need to call size()).

    You are already looping on it and have a convenient $data to do the same actions with

    $nextVisible = null;
    if (count($data) === 2000) {
        $lastEntry = end($data);
        $nextVisible = $lastEntry['id'];
    }