Firebase Integration With Laravel 6.x (Ubuntu 18.04)

Author - Webner
10.06.2020
|
0 Comments
||

Below are the steps to integrate Firebase with Laravel 6.x

Step 1

To integrate Firebase with Laravel we first need a Laravel project. Create a new Laravel project using the given composer command.

composer create-project --prefer-dist laravel/laravel firebase

Step 2

Goto the folder firebase and run below command.

composer require kreait/firebase-php ^4.0

Step 3

Setup firebase by signing up with Gmail account. It will bring you to the screen shown below.
firebase 1

Step 4

Click on the add new project and follow the below steps:
1.firebase 2
firebase 32.
firebase 43.
firebase 5
4. Wait for the completion of the process.
firebase 6

5. This is how the screen looks like when process is completed.
firebase 7

6. Create the database under the project as shown in the screenshot.
firebase 8

7. Choose one of these choices as per your requirement:
webner integration
8. For now we will choose test mode and will follow the steps given in screenshot:
laravel integration

9. Wait for the processing. After it is done, below screen will come up:
laravel integration 1

10. Now for the database integration setting please click on gear button on the top right side as shown in the screenshot.
laravel integration 2

11. Now follow the steps shown in the screenshots:
laravel integration 3

12. Click the Service Account tab shown in the Settings page.
laravel integration 4

13. Data under Service Account looks like this –
laravel integration 5

14. Note the database url shown in this screenshot as it is required for integration. Generate Private Key button will download a json file on your system, this file has the configuration details, we need to locate the service account:
laravel integration 6

Content of json file looks like this:

{
"type": "service_account",
"project_id": "project_id",
"private_key_id": "55ds6ds2dsad6d6dsad23sad3sa6d5ddsa3",
"private_key": "-----BEGIN PRIVATE KEY-----\nMJIIFDSDUFJiojNNIOKNLLKNKLNkllkknln\nKJNKJNJN++ojkkjhjkjkKLLKJKLJKLJ+kjh\nsnbjksahuddssadnkkJHSAKJDASJ02422+ADSljkj\n-----Going on this long -----\nB77tu2DPbAMN1gTdImwyYw==\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-somethinglikethis.com",
"client_id": "1231546532132165778",
"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/firebase-something-over-here-gserviceaccount.com"
}

This is all we need from firebase end. We’ll now turn back to laravel project.

Step 5

Open the project in a text editor that you like and then go to .env file and paste this code with all the correct information from the json as well as from settings tab on the site-

FIREBASE_DATABASE_URL=
FIREBASE_PROJECT_ID=
FIREBASE_PRIVATE_KEY_ID=
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMJIIFDSDUFJiojNNIOKNLLKNKLNkllkknln\nKJNKJNJN++ojkkjhjkjkKLLKJKLJKLJ+kjh\nsnbjksahuddssadnkkJHSAKJDASJ02422+ADSljkj\n-----Going on this long -----\nB77tu2DPbAMN1gTdImwyYw==\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=
FIREBASE_CLIENT_ID=
FIREBASE_CLIENT_x509_CERT_URL=

Step 6

Now under the app directory of the Laravel project create a new directory named Services and add a file to it(like FirebaseService.php). Paste the following code under the class.

public function __construct()
{
try {
$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();
$this->database = $this->firebase->getDatabase();
} catch (Exception $e) {
Log::error('Exception in __construct in ContactController --- '.$e->getMessage());
}
}

Make sure to include these namespaces-

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;

laravel integration 7

Step 7

Run below command to add provider for registering service that we created:
php artisan make:provider FirebaseServiceProvider

Step 8

When you hit enter, FirebaseServiceProvider.php file will be created under app/Providers directory. Now, go to FirebaseServiceProvider.php file and in the file under register function, register your service. Example of the code is shown below:
<?php
namespace App\Providers;
use App\Services\FirebaseService;
use Illuminate\Support\ServiceProvider;
use App\Observers\UserFavouriteObserver;
class FirebaseServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->singleton('FirebaseService', function () {
return new FirebaseService();
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}

Step 9

Do not forget to register your provider class in config/app.php file in providers array-

App\Providers\FirebaseServiceProvider::class

Step 10

Clear the cache of project using following commands:

php artisan cache:clear
php artisan config:cache

Step 11

Start the server using php artisan serve command.

Step 12

For testing purposes, create a controller using this command-

php artisan make:controller FirebaseController

Step 13

In your app/Http/Controllers/FirebaseController, paste the following code –
<?php
namespace App\Http\Controllers;
use App\Services\FirebaseService;
use Illuminate\Http\Request;
class FirebaseController extends Controller
{
private $fire;
private $database;
function __construct(FirebaseService $fire)
{
$this->fire = $fire;
$this->database = $fire->getDatabase();
}
function test(){
try {
$newPost = $this->database
->getReference('blog/posts')
->push([
'title' => 'Laravel FireBase Test' ,
'category' => 'Laravel'
]);
return $newPost->getvalue()->toJson();
} catch (\Throwable $th) {
//throw $th;
}
}
}

Step 14

Assign a route to this method in web.php as shown below-
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/firebase', 'FirebaseController@test);

Step 15

When you go to this URL: http://localhost:8000/firebase the browser will show the following output:

Step 16

Go to firebase console you will find this in your database:
laravel integration 8

Yep! you did the integration. Enjoy Coding …… 🙂

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *