Integrate Google Firebase (Realtime Database, Dynamic Links, FCM, etc.) in Laravel

Last modified on May 22, 2020 1 min read

Firebase is a Backend-as-a-Service — BaaS — that started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform.

In this article, I’m going to share how to integrate Google Firebase in Laravel application. Let’s get started:

Table of Contents

  1. Create Firebase Project
  2. Install Package
  3. Create Controller
  4. Define Routes
  5. Run and Test

Create Firebase Project

Go to Firebase and create a project. After creating the project, go to the Setting->Project Settings->Service accounts. We need to download the Firebase Admin SDK configuration file.

Click “Generate new private key” and it will download in a JSON file. Rename the file as firebase_credentials.json.

Install Package

Open Laravel application in terminal and install kreait/laravel-firebase package:

composer require kreait/laravel-firebase

Move the firebase_credentials.json file to the public folder of you app. Open .env file and addFIREBASE_CREDENTIALS variable like this:

FIREBASE_CREDENTIALS=/path/public/firebase_credentials.json

I’m working on localhost and the file path: E:\laragon\www\laravel\public\firebase_credentials.json

Note: You can use config file too. Please read this configuration.

Create Controller

Let’s create a controller named FirebaseDBController:

php artisan make:controller FirebaseDBController

Open the controller from app\Http\Controllers folder and paste this code:

FirebaseDBController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FirebaseDBController extends Controller
{
    private $database;

    public function __construct() {
        $this->database = app('firebase.database');
    }

    /**
     * Insert data.
     */
    public function insert() {
        $newPost =  $this->database
            ->getReference('blog/posts')
            ->push([
                'title' => "Title of Article",
                'description' => "This is an article"
            ]);

        return response()->json($newPost->getvalue());
    }

    /**
     * Retrieve data.
     */
    public function getData() {
        $data = $this->database->getReference('blog/posts')->getvalue();

        return response()->json($data);
    }

    /**
     * Update data.
     */
    public function update() {
        $post_id = "-M56ibO-en8Z9O5ryzjK";

        // new values
        $postData = [
            'title' => 'My awesome post title',
            'description' => 'This text should be longer',
        ];

        $updates = [
            'blog/posts/'.$post_id => $postData,
        ];

        $update = $this->database->getReference()->update($updates);

        return response()->json($update->getvalue());
    }

    /**
     * Delete data.
     */
    public function delete() {
        $post_id = "-M56jWfY-f7mHJYc5MtL";

        $delete = $this->database->getReference('blog/posts/'.$post_id)->remove();
    }

    /**
     * Delete all data.
     */
    public function deleteAll() {
        $delete = $this->database->getReference('blog/posts')->remove();
    }
}

I’ve written CURD functions to store/delete data from realtime firebase database.

Define Routes

Let’s create some routes for the FirebaseDBController.

web.php
Route::prefix('firebase')->group(function () {
    Route::get('insert', '[email protected]');
    Route::get('get_data', '[email protected]');
    Route::get('update', '[email protected]');
    Route::get('delete', '[email protected]');
    Route::get('delete_all', '[email protected]');
});

Run and Test

Now run the project and visit the routes to check data is saving/deleting from realtime database or not.

I’ve visited http://example.test/firebase/insert and checked realtime database from firebase console:

So, firebase is connected to our Laravel app & realtime database is working. Like the realtime database, now you can test FCM, Dynamic Links, Auth etc. Just take a look at laravel-firebase’s documentation.

The article is over. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

19 Replies to “Integrate Google Firebase (Realtime Database, Dynamic Links, FCM, etc.)…”

  1. Hello. Thanks For Your Article.
    But I Got Error “Invalid service account specification”
    Can You Fix it?

    1. Hi Bayu. You are welcome.

      Please set correct path of firebase_credentials.json to the .env’s FIREBASE_CREDENTIALS. Check step 2 (Install Package).

      Thanks. 🙂

  2. Sir,
    Can you tell me how we fetch one record by providing id. Like that one user information get.

    1. Hi Trilok kumar,

      This is an example of retrieving one post data by ID:
      $post_id = "-M56jWfY-f7mHJYc5MtL";
      $data = $this->database->getReference('blog/posts/' . $post_id)->getvalue();

      Thank you. 🙂

  3. Sir, I am getting below error

    Illuminate\Contracts\Container\BindingResolutionException
    Target class [firebase.database] does not exist.

      1. Thank you sir for the quick response, that issue us fixed now but now I Got Error “Invalid service account specification”

        I have gone through all steps many times and I didn’t find any issue

        1. Hello Nazir brother,

          You’re welcome. You have to set correct firebase_credentials.json path. Please check step 2 (Install Package). Let me know if it works or not.

          Thanks. 🙂

      1. boss i have shared another error please help out can call to a member function getReference() on array

  4. Hi. Thanks for the article. I would like to ask if you can setup Cloud Firestore from the GCP console (instead of creating a new firebase app) and then using that directly with a service account?

Leave a Reply

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