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

Laravel Firebase Laravel Package

kreait/laravel-firebase

Laravel package integrating the Firebase PHP Admin SDK. Configure via service account credentials, access Firebase services through Laravel-friendly bindings, and support multiple Firebase projects. Maintained under beste org; namespace/package name unchanged.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require kreait/laravel-firebase
    
  2. Publish the config (optional but recommended for customization):
    php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config
    
  3. Configure .env with your Firebase project details:
    FIREBASE_DATABASE_URL=https://your-project.firebaseio.com
    FIREBASE_CREDENTIALS=storage/app/firebase-auth.json  # Path to your service account JSON
    
  4. First use case: Access Firebase Auth in a controller:
    use Kreait\Laravel\Firebase\Facades\Firebase;
    
    public function createUser()
    {
        $auth = Firebase::auth();
        $user = $auth->createUser([
            'email' => 'user@example.com',
            'password' => 'securepassword123',
        ]);
        return response()->json($user);
    }
    

Implementation Patterns

Dependency Injection

Use Laravel's DI container for type-hinted Firebase components:

use Kreait\Firebase\Auth;
use Kreait\Laravel\Firebase\Facades\Firebase;

class UserService {
    public function __construct(private Auth $auth) {}

    // Use $auth directly
}

Facade Usage

Leverage the Firebase facade for quick access:

// Default project
$auth = Firebase::auth();
$firestore = Firebase::firestore();

// Specific project
$appAuth = Firebase::project('app')->auth();

Multi-Project Workflows

Configure multiple projects in config/firebase.php:

'projects' => [
    'app' => [
        'database_url' => 'https://app-project.firebaseio.com',
        'credentials' => storage_path('app/app-credentials.json'),
    ],
    'admin' => [
        'database_url' => 'https://admin-project.firebaseio.com',
        'credentials' => env('FIREBASE_ADMIN_CREDENTIALS'),
    ],
],

Common Patterns

  1. Firestore Queries:
    $collection = Firebase::firestore()->collection('users');
    $snapshot = $collection->where('role', '==', 'admin')->get();
    
  2. Storage Uploads:
    $storage = Firebase::storage();
    $bucket = $storage->bucket('my-bucket');
    $bucket->upload('local-file.jpg', 'remote-file.jpg');
    
  3. Messaging:
    $messaging = Firebase::messaging();
    $message = $messaging->createMessage([
        'token' => 'device-token',
        'notification' => ['title' => 'Hello', 'body' => 'World'],
    ]);
    $messaging->send($message);
    

Integration Tips

  • Cache Tokens: Enable token caching in config/firebase.php:
    'auth' => [
        'cache_tokens' => true,
    ],
    
  • HTTP Middlewares: Add Guzzle middlewares for request logging:
    'http_client_options' => [
        'middlewares' => [
            \Kreait\Firebase\Middleware\LoggingMiddleware::class,
        ],
    ],
    
  • Tenant Awareness: Use FIREBASE_AUTH_TENANT_ID for multi-tenant auth:
    FIREBASE_AUTH_TENANT_ID=tenant123
    

Gotchas and Tips

Common Pitfalls

  1. Credentials Auto-Discovery:

    • If using GOOGLE_APPLICATION_CREDENTIALS, ensure the path is absolute or properly resolved.
    • Relative paths (e.g., firebase-auth.json) are resolved via base_path()—test on Windows if using relative paths.
  2. Project Selection:

    • Always specify the project when using multiple configurations:
      // ❌ Avoids default project
      $auth = Firebase::project('app')->auth();
      
    • Facade methods default to the first project in config/firebase.php.
  3. PHP Version:

    • Requires PHP 8.3+ (as of v7.0.0). Check your composer.json constraints.
  4. Deprecated Facades:

    • Old facades (FirebaseAuth, FirebaseDatabase, etc.) are removed. Use Firebase::auth() instead.
  5. Firestore Database Name:

    • Override the default (default) database name in config:
      'firestore' => [
          'default_database' => 'production',
      ],
      

Debugging Tips

  • Enable HTTP Debugging:

    FIREBASE_HTTP_DEBUG_LOG_CHANNEL=stack
    

    Logs requests/responses to Laravel’s log channels.

  • Token Caching Issues:

    • Clear cached tokens with:
      php artisan cache:clear
      
    • Disable caching temporarily in config/firebase.php to test live auth.
  • Permission Errors:

    • Ensure your service account has Editor or Owner roles in Firebase Console.
    • Verify the project_id in credentials matches your Firebase project.

Configuration Quirks

  1. Credentials Array:

    • When using credentials as an array, ensure all required fields are present (e.g., private_key must include -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----).
  2. Environment Variables:

    • FIREBASE_DATABASE_URL is required for Realtime Database. Firestore does not need this.
  3. HTTP Timeouts:

    • Default timeout is 30 seconds (changed in kreait/firebase v6.7.0). Adjust in http_client_options:
      'http_client_options' => [
          'timeout' => 60, // seconds
      ],
      

Extension Points

  1. Custom Factories:

    • Extend the Firebase facade to add project-specific methods:
      Firebase::extend('custom', function () {
          return Firebase::project('app')->auth()->customMethod();
      });
      
  2. Middleware Injection:

    • Add custom Guzzle middlewares for retries or logging:
      'http_client_options' => [
          'middlewares' => [
              \App\Firebase\RetryMiddleware::class,
          ],
      ],
      
  3. Event Listeners:

    • Listen to Firebase events (e.g., Auth state changes) via Laravel events:
      Firebase::auth()->onAuthStateChanged(function ($user) {
          event(new UserLoggedIn($user));
      });
      
  4. Testing:

    • Mock Firebase components in tests using Laravel’s mocking:
      $this->mock(Firebase::class)->shouldReceive('auth')->andReturn($mockAuth);
      
    • Use FirebaseTestCase from the package for base test setup.

Performance Tips

  • Batch Writes: Use Firestore’s batch() for multiple writes:
    $batch = Firebase::firestore()->batch();
    $batch->set($batch->document('users/1'), ['name' => 'John']);
    $batch->commit();
    
  • Pagination: For large datasets, use Firestore’s limit() and cursor:
    $snapshot = $collection->limit(100)->get();
    
  • Offline Persistence: Enable in config for Firestore:
    'firestore' => [
        'settings' => [
            'cache_size_bytes' => Firebase\Firestore\CacheSize::CACHE_SIZE_UNLIMITED,
        ],
    ],
    
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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation