skip to Main Content

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 GoogleCloudFirestoreQuerySnapshot::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

2

Answers


  1. You’re getting the following error:

    Call to undefined method GoogleCloudFirestoreQuerySnapshot::count()

    Because the QuerySnapshot doesn’t contain a count() function. On the other hand, the Query class contains a count() function. So if you want to counter the documents that a query returns, call count() directly on the Query object.

    Login or Signup to reply.
  2. 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'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search