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

kreait/firebase-php

Unofficial Firebase Admin SDK for PHP. Manage authentication, users, custom tokens, and verify ID tokens; send Cloud Messaging notifications; work with Realtime Database, Cloud Storage, and Remote Config. Built on Google APIs with Laravel-friendly support.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install the package via Composer: composer require kreait/firebase-php. Ensure you’re using PHP 8.0+ and have ext-json enabled.
  2. Set up credentials: Download a service account JSON file from the Firebase Console (Project Settings > Service Accounts), and place it outside your web root.
  3. Configure in Laravel: In config/services.php, add:
    'firebase' => [
        'credential' => env('FIREBASE_CREDENTIAL', storage_path('app/firebase-admin.json')),
        'database_uri' => env('FIREBASE_DATABASE_URL', 'https://your-project-id.firebaseio.com'),
        'storage_bucket' => env('FIREBASE_STORAGE_BUCKET', 'your-project-id.appspot.com'),
    ],
    
    Or use Laravel’s config()->set() dynamically for flexibility.
  4. First use: Create a factory and get a service—e.g., for Auth:
    $firebase = (new Factory)->withServiceAccount(config('services.firebase.credential'));
    $auth = $firebase->getAuth();
    $user = $auth->getUserByEmail('user@example.com');
    
    Start with auth or FCM—they’re the most common day-to-day needs.

Implementation Patterns

  • Laravel Service Providers & Factories: Register a singleton Firebase instance in a service provider (e.g., FirebaseServiceProvider) for consistent access:
    $this->app->singleton(\Kreait\Firebase\Factory::class, function () {
        return (new \Kreait\Firebase\Factory)
            ->withServiceAccount(config('services.firebase.credential'))
            ->withDatabaseUri(config('services.firebase.database_uri'));
    });
    
  • Repository Layer for Firestore/RTDB: Abstract data access behind repositories—e.g., FirestoreUserRepository—to decouple business logic from SDK calls. Use DocumentReference and CollectionReference for type-safe queries.
  • FCM with Jobs: Dispatch notifications via queued jobs (e.g., SendFirebaseNotification) for reliability. Leverage topic messaging for broadcast ($messaging->sendToTopic('news', $message)) and token-based for targeted sends.
  • Testing with Emulators: Configure emulators locally via environment variables (FIREBASE_EMULATOR_HOST, FIREBASE_DATABASE_EMULATOR_HOST) and override Factory initialization in testing environment to run integration tests without cost.
  • Middleware for Auth Validation: Use $auth->verifyIdToken($token) in API middleware to validate Firebase ID tokens and hydrate the user into the request.

Gotchas and Tips

  • Credential Security: Never commit the JSON file or expose it via env vars in logs. Use storage_path() or environment-specific paths; rotate credentials if compromised.
  • Timezone & Timestamps: Firestore timestamps are Google\Type\DateTime objects—always convert to native PHP DateTimeImmutable with ->toDateTime() before storage or serialization to avoid JSON encoding surprises.
  • Error Handling: Use specific exceptions (Kreait\Firebase\Exception\InvalidArgumentException, Unavailable, NotFound) to handle partial failures—especially during batch operations (e.g., bulk FCM sends where some tokens may be invalid).
  • Retry Logic: By default, the SDK retries transient failures (e.g., network issues), but configure retries explicitly if needed:
    $factory = (new Factory)->withHttpOptions(['retries' => 3]);
    
  • Storage Bucket Quirks: Uploads to Cloud Storage require finfo_open() and proper file MIME detection. Use StorageObject::upload($filePath, ['predefinedAcl' => 'publicRead']) for simplicity—but avoid public ACLs in production.
  • Unit Testing: Mock only the high-level interfaces (e.g., \Kreait\Firebase\Auth)—not low-level HTTP calls. Use Factory::withServiceAccount() to inject test credentials (e.g., mock service accounts) for fast, isolated tests.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport