How to integrate Laravel with Google Firebase

Javier Núñez
Apr 5 · 4 min read

This article explains how to register an application in Google Cloud Firebase and integrate it in a Laravel application

0. INTRODUCTION

is a cloud service that gives you all the tools you need to support your APP with Authentication, Database, Analytics, Data and State synchronization, Messaging (push notifications), etc.

In this article I will explain how to integrate Firebase on a Laravel project based as the experience we had in during a project development.

1. FIREBASE APP REGISTRATION 🔥

  1. Go to and click on Add Project

2. Type the name on your project and click on “Create Project”.

3. When the project is ready click on “Continue”

4. Then you should go to to see service accounts. There you should see your project service account. Now you can click on the three dots menu to create your key. That will download a JSOn file with all the credentials we will need for the several steps:

The JSON file you will download will have these data:

{
"type": "service_account",
"project_id": "1234",
"private_key_id": "1234",
"private_key": "YOUR_PRIVATE_KEY",
"client_email": "email@appspot.gserviceaccount.com",
"client_id": "1234",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/YOUR_PROJECT_URL"
}

2. FIREBASE SDK ⚙

You can find the source code and github package for Firebase PHP Sdk here:

You can install this package doing:

composer require kreait/firebase-php

And you are ready to go.

You can find all the documentation about this SDK here:

3. FIREBASE SERVICE

To communicate with Firebase, you should need to create a Service, that will handle all requests done through the Firebase PHP SDK. It’s a level of abstraction that gives us a more specific application interface.

So, let’s go, create a FirebaseService.php file in app/Services with this content:

<?php

namespace
App\Services;

use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Kreait\Firebase\ServiceAccount;

class FirebaseService
{
public function __construct()
{

}
}

We will need some credentials to authenticate the service. We will add a new key in config/services.php with the following info:

// We need to provide default values to validate types
'firebase' => [
'database_url' => env('FIREBASE_DATABASE_URL', ''),
'project_id' => env('FIREBASE_PROJECT_ID', ''),
'private_key_id' => env('FIREBASE_PRIVATE_KEY_ID', 'your-key'),
// replacement needed to get a multiline private key from .env
'private_key' => str_replace("\\n", "\n", env('FIREBASE_PRIVATE_KEY', '')),
'client_email' => env('FIREBASE_CLIENT_EMAIL', 'e@email.com'),
'client_id' => env('FIREBASE_CLIENT_ID', ''),
'client_x509_cert_url' => env('FIREBASE_CLIENT_x509_CERT_URL', ''),
]

You will get this information from the JSON loaded from firebase on Step 1.

Now we are ready to config the service on our FirebaseService.php

<?php

namespace
App\Services;

use Exception;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Exception\Auth\EmailExists as FirebaseEmailExists;

class FirebaseService
{
/**
*
@var Firebase
*/
protected
$firebase;

public function __construct()
{
$serviceAccount = ServiceAccount::fromArray([
"type" => "service_account",
"project_id" => config('services.firebase.project_id'),
"private_key_id" => config('services.firebase.private_key_id'),
"private_key" => config('services.firebase.private_key'),
"client_email" => config('services.firebase.client_email'),
"client_id" => config('services.firebase.client_id'),
"auth_uri" => "https://accounts.google.com/o/oauth2/auth",
"token_uri" => "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url" => "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url" => config('services.firebase.client_x509_cert_url')
]);

$this->firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri(config('services.firebase.database_url'))
->create();
}
}

If we want to, for example, authenticate an email and password agains Firebase, we can do it like this:

<?php

namespace
App\Services;

use Exception;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Exception\Auth\EmailExists as FirebaseEmailExists;

class FirebaseService
{

/**
*
@var Firebase
*/
protected
$firebase;

public function __construct()
{
$serviceAccount = ServiceAccount::fromArray([
"type" => "service_account",
"project_id" => config('services.firebase.project_id'),
"private_key_id" => config('services.firebase.private_key_id'),
"private_key" => config('services.firebase.private_key'),
"client_email" => config('services.firebase.client_email'),
"client_id" => config('services.firebase.client_id'),
"auth_uri" => "https://accounts.google.com/o/oauth2/auth",
"token_uri" => "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url" => "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url" => config('services.firebase.client_x509_cert_url')
]);

$this->firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri(config('services.firebase.database_url'))
->create();
}

/**
* Verify password agains firebase
*
@param $email
*
@param $password
*
@return bool|string
*/
public function
verifyPassword($email, $password)
{
try {
$response = $this->firebase->getAuth()->verifyPassword($email, $password);
return $response->uid;

} catch(FirebaseEmailExists $e) {
logger()->info('Error login to firebase: Tried to create an already existent user');
} catch(Exception $e) {
logger()->error('Error login to firebase: ' . $e->getMessage());
}
return false;
}
}

Finally, you need to register your service. We can create a ServiceProvider for that, so let’s create a FirebaseServiceProvider.php in app/Providers:

<?php

namespace
App\Providers;

use App\Services\FirebaseService;
use Illuminate\Support\ServiceProvider;
use App\Observers\UserFavouriteObserver;

class FirebaseServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
*
@return void
*/
public function
boot()
{

}

/**
* Register any application services.
*
*
@return void
*/
public function
register()
{
$this->app->bind('FirebaseService', function () {
return new FirebaseService();
});
}
}

Now add this service provider to config/app.php providers array:

App\Providers\FirebaseServiceProvider::class,

That’s all, if you have any comment or question, I will be happy to answer. I hope it was helpful for you :)

Javier Núñez

Written by

Laravel | PHP | VueJS | Building nice things at www.square1.io