Google Firebase is a realtime database. It manages the database operations in the realtime. Basically, it is a NoSQL database that stores data in the JSON format. The JSON data is a combination of key/value pairs. So, there is no restriction to store data in the Firebase in real-time. However, in the Laravel, it is easy to control and secure the data in the database. Through, this tutorial, I am going to show, how you can integrate the Firebase realtime database with the Laravel 6 application. We have already seen how to create RESTful APIs in Laravel 6 using Passport authentication. So, go ahead with this tutorial.

Prerequisites

Generally, for creating this project you required –

Composer

PHP <=7.3.9

Google Firebase Realtime Database

A Web server (Apache, NGINX) for testing.

You must have a basic concept of the Laravel 6 application structure.

Before creating a new project in Laravel 6, let’s dive into Firebase and its features. I am just going to give you an overview of the Firebase.

Firebase Realtime Database

Firebase was established in 2012 as a real-time database architecture. It is managed by Google. Most importantly, it synchronizes the application to the database in real-time. It is a NoSQL database. The SQL database manages data in the form of rows and columns. Basically the rows and columns form table. However, the data that we store in the SQL databases are in the form of rows and columns. In the case of SQL databases. If you want to add some extra value in the existing database schema. Then it is not possible. The reason is the fixed set of columns that have already defined in the schema. But in the case of the Firebase, you can add data in the realtime. It will not restrict you to put the extra value as per your application.

Create a New Laravel 6 Project

Now, we will create a new application in Laravel 6. So, just open the terminal and create a new Laravel 6 project.

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

Laravel 6 Firebase Project Setup

It will take a few minutes to add the files to your project.

Laravel 6 Login and Registration with Authentication

Add Firebase Dependency in Laravel 6

For integrating the Firebase in Laravel 6, you will be required to add the dependency. Now, just navigate to your project directory. Inside the project, install the dependencies by hitting the following command in the terminal.

composer require kreait/firebase-php

It will take some time to install the necessary packages inside your project.

Add Firebase Dependency in Laravel 6

Setup Google Firebase For Laravel 6 Project

For Firebase setup you need to sign in with your Google account. Now, open the Google Firebase console. You will be redirected to the official page that will look like as shown below. Click on Create a project.

Google Firebase

Name your project and click to continue button.

Enter Project Name

Next, it will ask you to enable Google analytics. It is recommended to enable, now click on Continue.

Enable Analytics For Project

The project setup will be finished.

Project Setup Finish

After finishing the project setup, you will need to create a database.

How to Upload Files and Images in Laravel 6 with Validation

Create Database in Firebase

In the dashboard section, click on the Database. Now, under the Realtime Database, click on Create Database.

Create a New Database in Firebase

Most importantly, you need to allow read and write permission for the database.

Security Rules For Realtime Database

Laravel 6 CRUD Application with Form Validation

Generate API Key

In the next step, we’ll require to generate the API key for our Laravel 6 application. Go to the Setting->Project Settings->Service accounts

Generate API Key

When you will generate the key, it will download in a JSON file.

Laravel 6 Firebase Project Configuration

Once your file has been downloaded, open your project into your favorite editor. Now, inside the app\Http\Controllers paste the downloaded file. Because we will access this file into our controller.

I have renamed the file as FirebaseKey.json. For the demonstration purpose, I will create a controller in Laravel 6. Then, through that controller, I will save the data into the Firebase realtime database.

Create Laravel 6 Controller

For creating a new controller in Laravel 6 enter the below command in the terminal.

php artisan make:controller FirebaseController

After creating the controller this will be the file structure inside the Controllers folder.

Project Files after Creating Controller

Check Live E-mail Availability in PHP MySQL Using AJAX

Insert Data in Firebase Using Controller

In the next step, I will insert the data into the database using the controller (FirebaseController). Open the FirebaseController.php file and at the top add these two namespaces to use the Firebase resource.

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

Create Post Function

// -------------------- [ Insert Data ] ------------------ public function index() { $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/FirebaseKey.json'); $firebase = (new Factory) ->withServiceAccount($serviceAccount) ->withDatabaseUri('https://laravel6firebase.firebaseio.com/') ->create(); $database = $firebase->getDatabase(); $createPost = $database ->getReference('blog/posts') ->push([ 'title' => 'Laravel 6', 'body' => 'This is really a cool database that is managed in real time.' ]); echo '<pre>'; print_r($createPost->getvalue()); echo '</pre>'; }

In the above code, firstly, I have included the JSON key file. This is the same file that has been downloaded.

Then used the database URL that you can find inside the Database as shown below.

So, just copy it and paste it in the code.

Database Access URL

In the next line, I have added the database and table name. This is for a reference in which the data will be stored.

For inserting the data, I have created a static array of two fields. In the array, I have passed two keys with values.

The array value will be stored using the push() function.

function. At last, I have displayed the created data.

Add Route

Open the routes/web.php file. Add the below route for inserting the data into the realtime database.

Route::get('firebase','FirebaseController@index');

Further, save and run the project by hitting the below command.

php artisan serve

Open the browser and access the URL: http://localhost:8000/firebase

Data Inserted

If you got the result as an array like the above result. Then, it means the record has been inserted successfully.

Data in Realtime Database

So finally, we have successfully inserted the records in the Firebase realtime database.

Dependent Dropdown Selection Filter in PHP Using AJAX

Retrieve Data From Firebase

We can retrieve the inserted data from the realtime database. So, again create a new function for retrieving the data from the database.

// --------------- [ Listing Data ] ------------------ public function getData() { $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/FirebaseKey.json'); $firebase = (new Factory) ->withServiceAccount($serviceAccount) ->withDatabaseUri('https://laravel6firebase.firebaseio.com/') ->create(); $database = $firebase->getDatabase(); $createPost = $database->getReference('blog/posts')->getvalue(); return response()->json($createPost); }

Similarly, add a route for the above function.

Route::get('firebase-get-data', 'FirebaseController@getData');

Now access the below URL for retrieving the data from the realtime database. I have returned the data in the JSON format. It is just for demo purposes.

http://localhost:8000/firebase-get-data

Retrieving Data From Realtime database

How to Send Email in Laravel 6 Via Gmail Using SMTP

Here, is the full code of the controller.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Kreait\Firebase; use Kreait\Firebase\Factory; use Kreait\Firebase\ServiceAccount; use Kreait\Firebase\Database; class FirebaseController extends Controller { // -------------------- [ Insert Data ] ------------------ public function index() { $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/FirebaseKey.json'); $firebase = (new Factory) ->withServiceAccount($serviceAccount) ->withDatabaseUri('https://laravel6firebase.firebaseio.com/') ->create(); $database = $firebase->getDatabase(); $createPost = $database ->getReference('blog/posts') ->push([ 'title' => 'Laravel 6', 'body' => 'This is really a cool database that is managed in real time.' ]); echo '<pre>'; print_r($createPost->getvalue()); echo '</pre>'; } // --------------- [ Listing Data ] ------------------ public function getData() { $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/FirebaseKey.json'); $firebase = (new Factory) ->withServiceAccount($serviceAccount) ->withDatabaseUri('https://laravel6firebase.firebaseio.com/') ->create(); $database = $firebase->getDatabase(); $createPost = $database->getReference('blog/posts')->getvalue(); return response()->json($createPost); } }

This is the routes/web.php file.

Route::get('firebase','FirebaseController@index'); Route::get('firebase-get-data', 'FirebaseController@getData');

Conclusion

Finally, we integrated the Laravel 6 Application with the Firebase Realtime Database. We can use the Firebase for storing, retrieving, updating and deleting the data like other databases. The important feature of Firebase is to store data in the form of key and value which is a JSON format. We can use Firebase for push notification, user authentication, token access, etc. In our upcoming tutorials of the Laravel 6, we will learn some more advanced functionalities with the Firebase. So stay tuned with us. But if you find any problem with the integration of Firebase with Laravel 6. Then don’t hesitate to ask through the comments. I will help you immediately. In the next post, we will be creating the RESTful APIs for ToDo Application with Passport Auth.

Like this: Like Loading...