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

Firebase Php Laravel Package

ktamas77/firebase-php

PHP library for Firebase integration: access Realtime Database, Authentication and other Firebase services with a simple, lightweight API. Supports service account credentials, token handling, and common CRUD operations—useful for Laravel or any PHP app needing Firebase.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ktamas77/firebase-php
    

    Ensure your project has PHP 7.4+ and the ext-curl extension enabled.

  2. First Use Case: Initialize Firebase

    use Kreait\Firebase\Factory;
    use Kreait\Firebase\ServiceAccount;
    
    $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/serviceAccountKey.json');
    $firebase = (new Factory())
        ->withServiceAccount($serviceAccount)
        ->create();
    
  3. Where to Look First

    • Documentation: Official Docs (if available) or the GitHub README.
    • Examples: Check the tests/ directory in the package for real-world usage patterns.
    • API Reference: Focus on Kreait\Firebase\Firebase and its sub-services (e.g., Database, Storage, Auth).

Implementation Patterns

Common Workflows

1. Database Operations (Realtime Database)

$database = $firebase->database();
$ref = $database->getReference('users');

// Write data
$ref->set([
    'user1' => ['name' => 'John', 'email' => 'john@example.com']
]);

// Read data
$snapshot = $ref->get();
$users = $snapshot->getValue();

// Listen for changes
$ref->on('value', function ($snapshot) {
    $data = $snapshot->getValue();
    // Handle update
});

2. Authentication

$auth = $firebase->auth();
$user = $auth->createUser([
    'email' => 'user@example.com',
    'password' => 'securepassword123',
    'emailVerified' => false,
]);

// Sign in
$customToken = $auth->createCustomToken('uid');

3. Cloud Storage

$storage = $firebase->storage();
$bucket = $storage->bucket('my-bucket');

// Upload file
$bucket->upload(
    __DIR__.'/file.txt',
    ['name' => 'remote-file.txt']
);

// Download file
$file = $bucket->file('remote-file.txt');
$contents = $file->downloadToFile(__DIR__.'/downloaded.txt');

4. Firestore (if using the Firestore extension)

$firestore = $firebase->firestore();
$collection = $firestore->collection('posts');

// Add document
$collection->add(['title' => 'Hello World', 'content' => '...']);

// Query documents
$query = $collection->where('title', '==', 'Hello World');
$snapshot = $query->documents();

Integration Tips

  • Dependency Injection: Register the Firebase client in Laravel's service container for easy access:

    $app->singleton(Firebase::class, function ($app) {
        return (new Factory())
            ->withServiceAccount(ServiceAccount::fromJsonFile(storage_path('app/firebase-key.json')))
            ->create();
    });
    

    Then inject Kreait\Firebase\Firebase into controllers/services.

  • Environment Configuration: Store the service account key path in .env:

    FIREBASE_KEY_PATH=storage/app/firebase-key.json
    

    Load it dynamically:

    $serviceAccount = ServiceAccount::fromJsonFile(env('FIREBASE_KEY_PATH'));
    
  • Error Handling: Wrap Firebase operations in try-catch blocks to handle exceptions (e.g., Kreait\Firebase\Exception\FirebaseException):

    try {
        $snapshot = $ref->get();
    } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
        Log::error('Firebase error: ' . $e->getMessage());
        abort(500, 'Firebase operation failed');
    }
    

Gotchas and Tips

Pitfalls

  1. Service Account Key Permissions

    • Ensure the JSON key file has the correct permissions for the Firebase operations you intend to perform (e.g., database.readWrite, storage.objectAdmin).
    • Debug Tip: If you encounter permission errors, re-generate the key file in Firebase Console with the appropriate roles.
  2. Rate Limiting and Throttling

    • Firebase may throttle requests if you exceed limits. Implement exponential backoff for retries:
      use Kreait\Firebase\Exception\FirebaseException;
      use Kreait\Firebase\Exception\RateLimitExceeded;
      
      try {
          $snapshot = $ref->get();
      } catch (RateLimitExceeded $e) {
          sleep(2); // Wait before retrying
          retry();
      }
      
  3. Offline Persistence

    • The Realtime Database client enables offline persistence by default. If you don’t want this, disable it:
      $database = $firebase->database();
      $database->getReference()->setPersistenceEnabled(false);
      
  4. Timeouts

    • Default timeout for operations is 60 seconds. Adjust if needed:
      $database->getReference()->setTimeout(30); // 30 seconds
      
  5. CORS Issues

    • If using Firebase Storage with a web app, ensure CORS rules are configured in Firebase Console. Test locally with:
      firebase emulators:start
      

Debugging Tips

  • Enable Debug Logging Configure Monolog to log Firebase events:

    $factory = (new Factory())
        ->withLogger(new \Monolog\Logger('firebase', [
            new \Monolog\Handler\StreamHandler(storage_path('logs/firebase.log')),
        ]));
    
  • Check HTTP Requests Use tools like Postman or Charles Proxy to inspect raw HTTP requests/responses between your app and Firebase.

  • Validate JSON Keys Ensure the service account JSON key is valid and not corrupted. Test it with:

    firebase deploy --only functions --json-key path/to/serviceAccountKey.json
    

Extension Points

  1. Custom Middleware Add middleware to Firebase operations (e.g., logging, auth checks):

    $database->getReference()->addMiddleware(function ($request) {
        Log::info('Firebase DB request:', $request->getData());
        return $request;
    });
    
  2. Event Listeners Extend the package by listening to Firebase events (e.g., Realtime Database value changes):

    $ref->on('value', function ($snapshot) {
        event(new FirebaseDataUpdated($snapshot->getName(), $snapshot->getValue()));
    });
    
  3. Testing Use the Kreait\Firebase\Test\TestDouble trait to mock Firebase services in PHPUnit:

    use Kreait\Firebase\Test\TestDouble;
    
    class MyTest extends TestCase
    {
        use TestDouble;
    
        public function testFirebaseOperation()
        {
            $this->mockFirebaseDatabase();
            // Test logic here
        }
    }
    
  4. Async Operations For long-running tasks, use Laravel Queues to offload Firebase operations:

    dispatch(new UploadToFirebase($filePath, $bucketName));
    

    Then implement the job:

    public function handle()
    {
        $storage = app(Firebase::class)->storage();
        $bucket = $storage->bucket($this->bucketName);
        $bucket->upload($this->filePath, ['name' => 'uploaded-' . time() . '.txt']);
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui