Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cloud Firestore Laravel Package

google/cloud-firestore

Idiomatic PHP client for Google Cloud Firestore. Install via Composer and use the generated gRPC-based API to read/write documents, run queries, and manage data at scale. Part of the googleapis/google-cloud-php project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/cloud-firestore
    

    Ensure the gRPC extension is installed and enabled.

  2. Authentication: Configure credentials via environment variables (recommended) or service account JSON:

    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json');
    

    See Authentication Guide.

  3. First Query:

    use Google\Cloud\Firestore\FirestoreClient;
    
    $firestore = new FirestoreClient();
    $docRef = $firestore->collection('users')->document('user123');
    $snapshot = $docRef->snapshot();
    $data = $snapshot->data();
    

First Use Case: CRUD Operations

// Create
$docRef->set(['name' => 'John Doe', 'email' => 'john@example.com']);

// Read
$doc = $docRef->snapshot()->data();

// Update
$docRef->update(['email' => 'new@example.com']);

// Delete
$docRef->delete();

Key Starting Points:


Implementation Patterns

1. Repository Pattern Integration

Wrap Firestore operations in a Laravel repository to abstract away Firestore-specific logic:

class FirestoreUserRepository
{
    protected $firestore;

    public function __construct(FirestoreClient $firestore)
    {
        $this->firestore = $firestore;
    }

    public function findById(string $id)
    {
        return $this->firestore->collection('users')
            ->document($id)
            ->snapshot()
            ->data();
    }
}

Register in AppServiceProvider:

$this->app->singleton(FirestoreUserRepository::class, function ($app) {
    return new FirestoreUserRepository(new FirestoreClient());
});

2. Real-Time Updates with Listeners

Leverage Firestore’s real-time capabilities for live UI updates:

use Google\Cloud\Firestore\DocumentSnapshot;

$collection = $firestore->collection('chat_messages');
$listener = $collection->listen(function (DocumentSnapshot $snapshot) {
    // Handle real-time updates (e.g., broadcast via Laravel Echo)
    broadcast(new MessageUpdated($snapshot->data()));
});

Cleanup:

$listener->cancel();

3. Transactions for Atomic Operations

Use transactions for multi-document updates:

$firestore->runTransaction(function ($transaction) {
    $docRef = $firestore->collection('users')->document('user123');
    $snapshot = $docRef->snapshot();
    $data = $snapshot->data();

    $data['balance'] -= 100;
    $transaction->update($docRef, $data);

    // Update another document
    $otherDoc = $firestore->collection('orders')->document('order456');
    $transaction->update($otherDoc, ['status' => 'paid']);
});

4. Bulk Operations

For batch writes (e.g., imports):

$batch = $firestore->batch();
$batch->create($firestore->collection('users')->document(), ['name' => 'Alice']);
$batch->create($firestore->collection('users')->document(), ['name' => 'Bob']);
$batch->commit();

5. Querying with Filters

$collection = $firestore->collection('products');
$query = $collection->where('price', '>', 100)
    ->where('category', '==', 'electronics')
    ->orderBy('name')
    ->limit(10);

foreach ($query->documents() as $doc) {
    // Process results
}

6. Offline Persistence (Service Workers)

Use Firestore’s offline persistence for PWAs or mobile apps:

$firestore->enablePersistence();

7. Security Rules Integration

Define Firestore security rules in firestore.rules and validate in Laravel:

// Example: Check if user can access a document
$docRef = $firestore->collection('users')->document($userId);
$snapshot = $docRef->snapshot();
if (!$snapshot->exists() || $snapshot->data()['owner'] !== auth()->id()) {
    abort(403);
}

8. Event-Driven Architecture

Use Firestore triggers (Cloud Functions) for serverless workflows and listen in Laravel via:

  • Pub/Sub: Stream Firestore changes to a topic.
  • Webhooks: Poll for changes (less efficient).

9. Pagination

$lastDoc = null;
do {
    $query = $firestore->collection('posts');
    if ($lastDoc) {
        $query->startAfter($lastDoc);
    }
    $query->limit(10);
    $docs = $query->documents();
    foreach ($docs as $doc) {
        // Process
        $lastDoc = $doc;
    }
} while ($docs->count() > 0);

10. Testing

Use FirestoreTestCase or mock the client:

use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\Testing\FirestoreTestCase;

class UserRepositoryTest extends FirestoreTestCase
{
    public function testFindById()
    {
        $firestore = $this->createFirestoreClient();
        $firestore->collection('users')->document('test')->set(['name' => 'Test']);
        $this->assertEquals('Test', $firestore->collection('users')->document('test')->snapshot()->data()['name']);
    }
}

Gotchas and Tips

1. Authentication Pitfalls

  • Deprecated keyFile: Use GOOGLE_APPLICATION_CREDENTIALS env var or ApplicationDefaultCredentials instead.
    // ❌ Deprecated
    $firestore = new FirestoreClient(['keyFile' => 'path/to/key.json']);
    
    // ✅ Recommended
    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json');
    $firestore = new FirestoreClient();
    
  • Service Account Permissions: Ensure the account has roles/datastore.user or higher.

2. Performance Quirks

  • Batch Limits: Batches can contain up to 500 operations, but avoid large batches in loops (use pagination).
  • Query Limits: Firestore has query limits (e.g., 20 reads/sec per collection).
  • Indexing: Complex queries (e.g., IN, array-contains) require composite indexes. Use the Index Manager to check coverage.

3. Data Modeling

  • Denormalization: Firestore favors embedded data over joins. Duplicate fields (e.g., user_name in posts) to avoid GET loops.
  • Arrays: Avoid large arrays (use subcollections instead). Firestore has a 1MB document limit.
  • Timestamps: Use FirestoreTimestamp for server-side time:
    use Google\Cloud\Firestore\FirestoreTimestamp;
    $docRef->set(['created_at' => FirestoreTimestamp::now()]);
    

4. Real-Time Listeners

  • Memory Leaks: Always cancel listeners in destroy() or beforeDestroy():
    public function destroy()
    {
        $this->listener->cancel();
        parent::destroy();
    }
    
  • Throttling: Limit listener frequency (e.g., debounce UI updates).

5. Transactions and Retries

  • Retry Logic: Firestore transactions may fail due to conflicts. Implement exponential backoff:
    $attempts = 0;
    while ($attempts < 3) {
        try {
            $firestore->runTransaction($transaction);
            break;
        } catch (Exception $e) {
            $attempts++;
            sleep(2 ** $attempts); // Exponential backoff
        }
    }
    

6. Debugging

  • Enable Logging:
    $firestore = new FirestoreClient([
        'logger' => new \Monolog\Logger('firestore', [
            new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG),
        ]),
    ]);
    
  • Check Headers: Use x-goog-request-params for debugging (e.g., curl -v).

7. Laravel-Specific Tips

  • Service Provider Binding:
    $this->app->
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata