Weave 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

Firebase Admin SDK for PHP by kreait lets you access Firebase services like Auth, Firestore, Realtime Database, Storage, and Cloud Messaging from privileged server or cloud environments. Install with Composer: kreait/firebase-php ^8.0.

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. Version 8.5.0+ adds PSR-14 event dispatching—worth pinning to ^8.5 if you want lifecycle hooks for Auth, Messaging, and Remote Config. Version 8.6.0+ adds Remote Config experiment values and credential-free emulator support—pin ^8.6 if you run integration tests in CI or read experiment variants.
  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. In 8.6.0 the emulators no longer require real Google credentials (see Testing notes), but production paths are unchanged.
  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('[email protected]');
    
    Start with auth or FCM—they’re the most common day-to-day needs.
  5. Wire up the event dispatcher (new in 8.5.0): The factory accepts a PSR-14 dispatcher; once provided, Auth, Messaging, and Remote Config emit events you can listen for:
    $factory = (new Factory)
        ->withServiceAccount(config('services.firebase.credential'))
        ->withEventDispatcher($psr14Dispatcher); // required, otherwise no events fire
    
    Nothing is dispatched unless you opt in—so add this early rather than retrofitting listeners later.

Implementation Patterns

  • Laravel Service Providers & Factories: Register a singleton Firebase instance in a service provider (e.g., FirebaseServiceProvider) for consistent access. As of 8.5.0, inject the dispatcher here so every resolved service emits events:
    $this->app->singleton(\Kreait\Firebase\Factory::class, function ($app) {
        return (new \Kreait\Firebase\Factory)
            ->withServiceAccount(config('services.firebase.credential'))
            ->withDatabaseUri(config('services.firebase.database_uri'))
            ->withEventDispatcher($app->make(\Psr\EventDispatcher\EventDispatcherInterface::class));
    });
    
    Bind EventDispatcherInterface to a PSR-14 adapter wrapping Laravel’s dispatcher (see Gotchas) so listeners live in app/Listeners like normal Laravel code.
  • Event-Driven Reactions (8.5.0): Rather than polling or wrapping every SDK call in try/catch, subscribe to SDK events:
    • Auth: react to user created/updated/deleted, refresh-token revocation, and sent email action links—ideal for mirroring Firebase users into a local users table, audit logs, or invalidating cached profiles.
    • Messaging: listen for sent messages and validation errors—great for marking stale FCM tokens as unusable without parsing exceptions.
    • Remote Config: listen for published and rolled-back templates—use this to bust a config cache or notify ops. Keep listeners queueable (ShouldQueue) so a slow audit write doesn’t block the SDK call.
  • Remote Config with Experiment Values (8.6.0): The Remote Config API now surfaces experiment values alongside regular parameters. Resolve config through a small service rather than calling the SDK inline, and decide explicitly how experiment variants participate in your fallback chain (e.g. experiment value → parameter value → local default). Cache the resolved template briefly (Cache::remember) so per-request lookups don’t hammer the API, and invalidate on the template-published event.
    $template = $remoteConfig->getTemplate();
    $parameters = $template->getParameters(); // now includes experiment-backed entries
    
  • 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. Pair this with the new messaging events to reconcile delivery results.
  • Testing with Emulators (improved in 8.6.0): Configure emulators locally via environment variables (FIREBASE_EMULATOR_HOST, FIREBASE_DATABASE_EMULATOR_HOST) and override Factory initialization in the testing environment. As of 8.6.0:
    • Realtime Database and Auth emulators work without Google credentials or an OAuth token exchange—so CI (including external contributor PRs) needs no service account secret.
    • Custom token generation still requires signing credentials, even against the Auth emulator. Keep a fake/test keypair for that path, or skip those assertions in CI.
    • The package’s new TESTING.md and helper scripts are the fastest way to reproduce a known-good emulator setup before debugging your own. Use a fake/recording PSR-14 dispatcher in tests to assert which Firebase events fired.
  • Middleware for Auth Validation: Use $auth->verifyIdToken($token) in API middleware to validate Firebase ID tokens and hydrate the user into the request. The new refresh-token-revocation events give you a push-based signal to force logout in your own session store.

Gotchas and Tips

  • Laravel’s Dispatcher Is Not PSR-14: Illuminate\Contracts\Events\Dispatcher does not implement Psr\EventDispatcher\EventDispatcherInterface. You need an adapter—e.g. symfony/psr-event-dispatcher-adapter (new PsrEventDispatcherAdapter($app['events'])) or a tiny 15-line wrapper—otherwise withEventDispatcher() fails on type-hint. Note the adapter dispatches the event object itself, so Laravel listeners should type-hint the Firebase event class rather than receiving (Event $event) style parameters.
  • Events Are Opt-In: If you don’t call withEventDispatcher(), 8.5.0+ behaves as before—no events, no listeners, no errors. Conversely, if you do provide one, an exception thrown inside a listener can surface from an unrelated SDK call, so keep listener logic defensive and queued.
  • Event Class Names: The 8.5.0 notes describe behaviours rather than exact FQCNs. Inspect the package’s Event namespaces (Kreait\Firebase\Auth\Event, ...\Messaging\Event, ...\RemoteConfig\Event) after upgrading and register listeners against those classes; don’t guess class names from the changelog.
  • Emulator ≠ Production Parity: The 8.6.0 credential-free emulator support is a testing convenience, not a behavioural guarantee. Auth emulator flows won’t validate real token signing, and custom token generation still demands signing credentials—don’t let green emulator tests hide a production credential/config problem. Guard any emulator wiring behind app()->environment('testing') so it can never activate in production.
  • Remote Config Experiments Move Under You: Experiment values can change without a deploy, and can be assigned per user/audience. Never persist an experiment value into durable business state (prices, entitlements) without recording the variant you saw; treat the template as cacheable-but-volatile and keep a hardcoded default for every key you read.
  • 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. The same applies to timestamps carried on event payloads.
  • 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). Where a messaging validation-error event fires, treat it as a complement to exception handling, not a replacement.
  • 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]);
    
    Retried calls can emit events more than once—make listeners idempotent.
  • 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. For event assertions, bind a spy dispatcher and check it received the expected Firebase events rather than asserting on Laravel’s global event fake.
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.
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core