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
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.
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.
Name your project and click to continue button.
Next, it will ask you to enable Google analytics. It is recommended to enable, now click on Continue.
The project setup will be finished.
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.
Most importantly, you need to allow read and write permission for the 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
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.
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.
- 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.
- 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
If you got the result as an array like the above result. Then, it means the record has been inserted successfully.
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
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.
Muna Tamang says
This post was really helpful. Thank You for this post! Could you please post the tutorial on firestore integration in laravel?
Umesh Rana says
Thank you for your appreciation. Definitely, I will post a tutorial on the firestore integration as soon as possible.
Piyush says
Hi,
I was able to set up firebase with Laravel, following your tutorial. But I want realtime changes to show in my page. When I change through firebase interface, it should reflect in my firebase-get-data route, without having to refresh the page. Please help with that.
Regards,
mohamad says
A very useful post. I would like to mention when I try to use withDatabaseUri() I add the project name which returns unauthorized request… I have to use a database URL provided by firebase runtime
Ankit Kumar says
I am facing this issue. Please help me
Kreait Firebase Exception Database DatabaseError (400)
invalid_grant
Previous exceptions
Client error: `POST resulted in a `400 Bad Request` response: {“error”:”invalid_grant”,”error_description”:”Invalid JWT: Token must be a short-lived token (60 minutes) and in a reaso (truncated…) (400)
Umesh Rana says
I think you haven’t configured the Firebase Database properly that’s the permission issue.
Prajwal Maharjan says
how to i separate the serviceAccount and the firebase object so that i don’t have to write the same code over and over again?
Umesh Rana says
Simply create a function with return type and call the ServiceAccount there. Now, call that function where you want to get the value.
Prajwal Maharjan says
Is it possible to create and use a custom service so I can that use it across all the controllers.
Umesh Rana says
You can create a HelperController and simply define the function inside that Controller. Then you can use the controller function in any controller.
Suppose you have a controller named HelperController and inside this controller, you have the function as below –
public function myService() {
-- --- -- your code will go here -- --- --
}
Now, in the SecondController you can call the above function like –
app(\App\Http\Controllers\HelperController::class)->myService();
That’s it. This will be your global function.
Maryam says
Thank you for this useful tutorial. I have followed it and getting the following error “Call to private method Kreait\Firebase\ServiceAccount::fromJsonFile() from context ‘App\Http\Controllers\FirebaseController'” can you please let me know what could be the issue.
Umesh Rana says
I think you have not used the namespaces before calling the functions. Please use these namespaces inside your controller.
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Database;
I hope this will work.
Maryam says
Thank you so much for timely reply.
Yes i have added these but its not working for me, Also i am using Laravel 7.
Umesh Rana says
Would you like to share your code, so that I can check the actual errors? If it is possible then send me a screenshot of the error that you are getting.
Webroot Infosoft says
I am facing same issue, here is my code after
withServiceAccount($serviceAccount)
->withDatabaseUri(‘https://meetup-e3c55.firebaseio.com/’)
->create();
$database = $firebase->getDatabase();
$createPost = $database
->getReference(‘chat/meetup’)
->push([
‘title’ => ‘Laravel 6’,
‘body’ => ‘This is really a cool database that is managed in real time.’
]);
echo ”;
print_r($createPost->getvalue());
echo ”;
}
public function getData() {
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.’/FirebaseKey.json’);
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri(‘https://meetup-e3c55.firebaseio.com/’)
->create();
$database = $firebase->getDatabase();
$createPost = $database->getReference(‘blog/posts’)->getvalue();
return response()->json($createPost);
}
}
HJ says
Thanks for the great tutorial! I am getting this following error after following all steps:
syntax error, unexpected ‘$serviceAccount’ (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)
Here is my code:
withServiceAccount($serviceAccount)
->withDatabaseUri(‘MY DB URL”)
->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 ”;
print_r($createPost->getvalue());
echo ”;
}
HJ says
I just realized that I copied it without the function lol my bad!
Marco says
Hello i have the same problem precedently typed from another developer
“Call to private method Kreait\Firebase\ServiceAccount::fromJsonFile() from context ‘App\Http\Controllers\FirebaseController'”
I’m using laravel 7.
Edit the .env file and use the correct database name in the DB_DATABASE key.”
If you can help me quickly i’ll be grateful.
Umesh Rana says
Hi Marco,
Thanks to share your problem. It was working absolutely fine in Laravel 6 with the default Database credentials. Actually, when we use Firebase then Laravel manages the Firebase database and we no need to configure the local database. It seems that something changed over here. So, let me post a new tutorial on Laravel 7 with firebase.
abhi says
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.’/FirebaseKey.json’);
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri(”)
->createDatabase();
$database = $firebase->getDatabase();
$createPost = $database->getReference(‘people’)->getvalue();
return $createPost; but now we are not allowed to use this new factory(), so how can i change my code…
abhi says
how can i get data from firebase and store it in different tables.. and how to code without using new factory(),
Umesh Rana says
It was working absolutely fine in the Laravel 6. Let me post a same tutorial for Laravel 7. It seems something changed over here in the Laravel 7.