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
You’re getting the following error:
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, callcount()
directly on theQuery
object.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 ofcount()
you need to callsize()
).You are already looping on it and have a convenient
$data
to do the same actions with