Firebase RealTime Integration Laravel-5-x

By | January 11, 2020

Hello Coders !!, Scientists, This article, we will learn about Firebase RealTime Integration Laravel-5-x using google firebase Realtime database. The Firebase Realtime Database is a cloud-hosted database where Data is stored as JSON and synchronized in realtime to every connected client.

So when we need to use Real-time change on the web app or mobile app we will need it and it is faster than another database.

It can be used on a Real-time chat system, live location moving app like food delivery app or courier service, etc..

Install Laravel if not installed yet

 Please follow URL to Install Laravel

Once you will be finished with the laravel installation please follow below steps

Create Firebase account with Realtime database

Open Google Firebase it will look like below screenshot

Firebase RealTime Integration Laravel-5-x
Firebase console screen

Click on the “Create a project” button.

Firebase RealTime Integration Laravel-5-x
Make sure you choose free plan for initial testing
Firebase RealTime Integration Laravel-5-x
Create project with adding name from here this screen
Firebase RealTime Integration Laravel-5-x
This screen shows the project is created successfully.
Firebase RealTime Integration Laravel-5-x
After creating a project you will be redirected to this page.
Firebase RealTime Integration Laravel-5-x steps
Click on the marked “web app” button and follow the next step
Give a name on firebase web app
Give a name on firebase web app
Note: In this screen, you will get code in which you can use client-side js code.
Note: In this screen, you will get code in which you can use client-side js code.
Make sure this is a cloud firestore database. where firestore and realtime both are a different things.
Make sure this is a cloud firestore database. where firestore and realtime both are different things.

The above screen is for firestore database just for knowledge. here in this article, we will only learn about realtime databases where both are different things. so don’t get confused about it.

This screen defines the mode of environment based on need.
This screen defines the mode of environment based on need.
Here you can create a collection with nodes.
Here you can create a collection with nodes.
Write the collection name and continue to follow the next steps.
Write the collection name and continue to follow the next steps.
This is an example of collections
This is an example of collections
The collection will look like this as per the screenshot.
The collection will look like this as per the screenshot.
Here we need to click on the mentioned link to create a credential.
Here we need to click on the mentioned link to create a credential.

In this section, we will create a credential JSON file which can be used in the server-side operation of the code.

Clicking on create key it will open a popup like below
Clicking on create key it will open a popup like below
Choose JSON as a type and click on "CREATE" button
Choose JSON as a type and click on “CREATE” button

After following this step you will have the “credentials.json” file keep it some safe place in your PC we are going to use that file later in the next step.

Go to  RealTime database by selecting that option
Go to RealTime database by selecting that option
Nodes sample will be shown like this based on needs
Nodes sample will be shown like this based on needs

Now follow the below step to integrate the real-time database in laravel

Connect “credential.json” file to Laravel

Copy that “credentials.json” (or whatever name you kept) in /config folder.

Install below package for firebase

$ composer require kreait/firebase-php // I am using ^4.35 version based on requirement. 

Create Controller called FirebaseController

Run below command to create a controller

$ php artisan make:controller FirebaseController

Paste below code in the generated controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kreait\Firebase\Factory;

class FirebaseController extends Controller
{
    //

    public function index(){    			
    	$database = $this->getDbRef();

		$reference = $database->getReference('products');

		echo "<pre>";
		print_r($reference->getValue()); // Fetches the data from the realtime database);
		echo "<br/>";
		exit;
	}

	// this will set all nocdes on bulk when database is in intial stage like dumping data
	public function setNodes(){	
		$database = $this->getDbRef();

		$reference = $database->getReference('products');
		
		// add nodes initial
		$reference = $reference->set([
			'sku-1' => [
		    	'name' => 'bottol',
		    	'price' => '20'   
		    ],
		    'sku-2' => [
		    	'name' => 'cup',   
		    	'price' => '30'
		    ]
		]);

		echo "<pre>";
		print_r($reference->getValue()); // Fetches the data from the realtime database);
		echo "<br/>";
		exit;
	}


	// push node when data already exists
	public function pushNode(){	
		$database = $this->getDbRef();

		// push nodes on already added 
		$postData = [
		    'name' => 'tea cup',   
		    'price' => '40'
		];

		// Create a key for a new post
		$newPostKey = $database->getReference('products')->push()->getKey();

		$updates = [
		    'products/sku-3' => $postData		  
		];

		$reference = $database->getReference() // this is the root reference
		   ->update($updates);

		echo "<pre>";
		print_r($reference->getValue()); // Fetches the data from the realtime database);
		echo "<br/>";
		exit;		
	}

	// set values on specific nodes
	public function updateNodeValue(){	
		$database = $this->getDbRef();

		$reference = $database
		        ->getReference('products/sku-1/price')            
		        ->set('35');
		        
		echo "<pre>";
		print_r($reference->getValue()); // Fetches the data from the realtime database);
		echo "<br/>";
		exit;	
	}

	// set values on specific nodes
	public function removeNode(){	
		$database = $this->getDbRef();

		$reference = $database->getReference('products/sku-1')->remove();

		echo "<pre>";
		print_r($reference->getValue()); // Fetches the data from the realtime database);
		echo "<br/>";
		exit;	
    }


    // get database reference globally from function
    private function getDbRef(){
    	$factory = (new Factory)
			->withServiceAccount('../config/google-service-account.json')
			// The following line is optional if the project id in your credentials file
			// is identical to the subdomain of your Firebase project. If you need it,
			// make sure to replace the URL with the URL of your project.
			->withDatabaseUri('https://lara-fire-xxxxx.firebaseio.com');

		$database = $factory->createDatabase();

		return $database;
    }
}
?>

Make sure you will read all comments on the controller code provided above and replace related parameters as you need like database URL config file path etc.

I Have created variation options which include below operations

getDbRef # first and required method to get reference of database
index # this method list all the nodes from database
setNodes # This method is about to insert new nodes
pushNode # This method describes how to push node in existing node
updateNodeValue # Here you will learn how to update value of node
removeNode # To follow this you will get how to delete nodes

Now run project now

$ php artisan serve

Open /firebase URL to get the listing result of nodes based on your firebase realtime database.

Congratulations!! you learned laravel firebase realtime database integration.

Here you can find git repo in case you will need it.

So, this article is about the Firebase RealTime Integration Laravel-5-x.

One thought on “Firebase RealTime Integration Laravel-5-x

Leave a Reply

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