Connect Laravel with Firebase Real Time Database

 Connect Laravel with Firebase Real Time Database


Secure and efficient data retrieval is one of the fundamental requirements for a good app. Fortunately, developers have a number of options (for instance, framework level tools and secure DBMS) for implementing this requirement.

What is Firebase?

Firebase was founded in 2012 as a real-time architecture for syncing data between apps. It was acquired by Google in 2014. Originally, it was a part of Envolve, a real-time chat integration API. Overtime, the developers realized that the system was being used to more than just text messages. Realizing the potential of the system, they come up with the idea of Firebase as a separate entity from Envolve.

In this article , I will demonstrates how to connect Firebase Realtime Database in Laravel 5.5 (by using Admin SDK).

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.1
  • Google Firebase Realtime Database
  • Web server (Apache, NGINX or integrated PHP web server for testing).

I have installed my Laravel app on a Cloudways managed server because it has a Laravel optimized dev stack and advanced PHP hosting. If you do not have an account on Cloudways, sign up for free, and check out the following GIF to setup the server and application in just a few clicks.


How to Setup Firebase

Let’s start with signing up for a Gmail account. In the next tab, open the Firebase page for database settings and click the Visit Console button.

Next, in the next window, create a database project and provide information including project name. When done, click the Create Project button.

Wait for the project to be created and then continue. You will be automatically redirected to the Firebase Dashboard.

After successfully creating the project, go to the Database tab, click Rules to update read and write rules to true and then click the Publish button.

Generate the API Key

Firebase generates an  API key for your project that you can download and paste into http/Controller.

Click the User and permissions tab.

Next, click Support account and then click the Create Key button

The key will be created in JSON format and downloaded automatically. You can copy the this file to the http/controller folder of Laravel.

Laravel Composer Require

After setting up the Firebase database, go to the Laravel application and install kreait/firebase-php ^4.0. Open the SSH terminal and goto the public_root

Enter the following command:

  1. composer require kreait/firebase-php ^4.0

Alternatively, you can specify the Firebase Admin SDK as a dependency in your project’s existing composer.json file:

  1. {
  2. "require": {
  3. "kreait/firebase-php": "^4.0"
  4. }
  5. }


Create the Controller

After pasting the API Key in the Controller folder, go to the in SSH Terminal and type the following command to create the Controller:

php artisan make:controller FirebaseController

Next, paste the following code in the Controller file:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Kreait\Firebase;
  5. use Kreait\Firebase\Factory;
  6. use Kreait\Firebase\ServiceAccount;
  7. use Kreait\Firebase\Database;
  8. class FirebaseController extends Controller
  9. {
  10. //
  11. public function index(){
  12. $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/Laraveltesting-6aeda3a963f2.json');
  13. $firebase = (new Factory)
  14. ->withServiceAccount($serviceAccount)
  15. ->withDatabaseUri('https://laraveltesting-bd2b9.firebaseio.com/')
  16. ->create();
  17. $database = $firebase->getDatabase();
  18. $newPost = $database
  19. ->getReference('blog/posts')
  20. ->push([
  21. 'title' => 'Post title',
  22. 'body' => 'This should probably be longer.'
  23. ]);
  24. //$newPost->getKey(); // => -KVr5eu8gcTv7_AHb-3-
  25. //$newPost->getUri(); // => https://my-project.firebaseio.com/blog/posts/-KVr5eu8gcTv7_AHb-3-
  26. //$newPost->getChild('title')->set('Changed post title');
  27. //$newPost->getValue(); // Fetches the data from the realtime database
  28. //$newPost->remove();
  29. echo"<pre>";
  30. print_r($newPost->getvalue());
  31. }
  32. }
  33. ?>

Remember to replace the file path in fromJsonFile with your own file path. Also, replace the database URL with your database’s URL:

Set up the Route

Open  the Laravel routes/web.php file and update the following code:

  1. <?php
  2. /*
  3. |--------------------------------------------------------------------------
  4. | Web Routes
  5. |--------------------------------------------------------------------------
  6. |
  7. | Here is where you can register web routes for your application. These
  8. | routes are loaded by the RouteServiceProvider within a group which
  9. | contains the "web" middleware group. Now create something great!
  10. |
  11. */
  12. Route::get('/', function () {
  13. return view('welcome');
  14. });
  15. Route::get('/phpfirebase_sdk','FirebaseController@index');

Save all changes in the Laravel application and run your application to see the output in action:

 Firebase Database

Conclusion

I hope that by now you have a very good idea of using Firebase Realtime Database in Laravel project. 

Comments