Laravel RealTime CRUD Using Google Firebase

Last modified on June 7, 2020 5 min read

In this tutorial, I am going to show you the real-time CRUD using Google Firebase. Let’s follow these steps:

Table of Contents

  1. Create a Firebase Project
  2. Create a Laravel Project
  3. Register View Route
  4. Configure Firebase Setting
  5. Add a Blade File
  6. Run and Test

Step 1 : Create a Firebase Project

Let’s first create a firebase project and take firebase credentials. Go to
https://firebase.google.com/ and create a project.

Enter a project name and click “Create project” button.

Our firebase project has been created. Now click “Continue” button. On the Project Overview page, you will see like this:

From this page, select Web. Then you will see a popup window with the firebase web config credentials.

We have successfully created a Firebase project and got the necessary credentials.

Step 2 : Create a Laravel Project

Go to your project directory using CMD and run this command to create a Laravel project:

composer create-project --prefer-dist laravel/laravel laravelproject

Step 3 : Register View Route

Go to routes >> web.php and register this route:

web.php
<?php

Route::view('customers', 'customers');

Step 4 : Configure Firebase Setting

Now, we are configuring google firebase setting in our laravel application. so, open config/services.php file and set following configuration in this file.

services.php
'firebase' => [
    'api_key' => 'api_key', // Only used for JS integration
    'auth_domain' => 'auth_domain', // Only used for JS integration
    'database_url' => 'https://database_url.com/',
    'storage_bucket' => '', // Only used for JS integration
],

Step 5 : Add a Blade File

Navigate to resources >> views directory and create a file named “customers.blade.php”. Then open the file and paste this code:

customers.blade.php
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    <title>Laravel RealTime CRUD Using Google Firebase</title>

</head>
<body>

<div class="container" style="margin-top: 50px;">

    <h4 class="text-center">Laravel RealTime CRUD Using Google Firebase</h4><br>

    <h5># Add Customer</h5>
    <div class="card card-default">
        <div class="card-body">
            <form id="addCustomer" class="form-inline" method="POST" action="">
                <div class="form-group mb-2">
                    <label for="name" class="sr-only">Name</label>
                    <input id="name" type="text" class="form-control" name="name" placeholder="Name"
                           required autofocus>
                </div>
                <div class="form-group mx-sm-3 mb-2">
                    <label for="email" class="sr-only">Email</label>
                    <input id="email" type="email" class="form-control" name="email" placeholder="Email"
                           required autofocus>
                </div>
                <button id="submitCustomer" type="button" class="btn btn-primary mb-2">Submit</button>
            </form>
        </div>
    </div>

    <br>

    <h5># Customers</h5>
    <table class="table table-bordered">
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th width="180" class="text-center">Action</th>
        </tr>
        <tbody id="tbody">

        </tbody>
    </table>
</div>

<!-- Update Model -->
<form action="" method="POST" class="users-update-record-model form-horizontal">
    <div id="update-modal" data-backdrop="static" data-keyboard="false" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" style="width:55%;">
            <div class="modal-content" style="overflow: hidden;">
                <div class="modal-header">
                    <h4 class="modal-title" id="custom-width-modalLabel">Update</h4>
                    <button type="button" class="close" data-dismiss="modal"
                            aria-hidden="true">Γ—
                    </button>
                </div>
                <div class="modal-body" id="updateBody">

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light"
                            data-dismiss="modal">Close
                    </button>
                    <button type="button" class="btn btn-success updateCustomer">Update
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- Delete Model -->
<form action="" method="POST" class="users-remove-record-model">
    <div id="remove-modal" data-backdrop="static" data-keyboard="false" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel"
         aria-hidden="true" style="display: none;">
        <div class="modal-dialog modal-dialog-centered" style="width:55%;">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="custom-width-modalLabel">Delete</h4>
                    <button type="button" class="close remove-data-from-delete-form" data-dismiss="modal"
                            aria-hidden="true">Γ—
                    </button>
                </div>
                <div class="modal-body">
                    <p>Do you want to delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default waves-effect remove-data-from-delete-form"
                            data-dismiss="modal">Close
                    </button>
                    <button type="button" class="btn btn-danger waves-effect waves-light deleteRecord">Delete
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>


{{--Firebase Tasks--}}
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase.js"></script>
<script>
    // Initialize Firebase
    var config = {
        apiKey: "{{ config('services.firebase.api_key') }}",
        authDomain: "{{ config('services.firebase.auth_domain') }}",
        databaseURL: "{{ config('services.firebase.database_url') }}",
        storageBucket: "{{ config('services.firebase.storage_bucket') }}",
    };
    firebase.initializeApp(config);

    var database = firebase.database();

    var lastIndex = 0;

    // Get Data
    firebase.database().ref('customers/').on('value', function (snapshot) {
        var value = snapshot.val();
        var htmls = [];
        $.each(value, function (index, value) {
            if (value) {
                htmls.push('<tr>\
        		<td>' + value.name + '</td>\
        		<td>' + value.email + '</td>\
        		<td><button data-toggle="modal" data-target="#update-modal" class="btn btn-info updateData" data-id="' + index + '">Update</button>\
        		<button data-toggle="modal" data-target="#remove-modal" class="btn btn-danger removeData" data-id="' + index + '">Delete</button></td>\
        	</tr>');
            }
            lastIndex = index;
        });
        $('#tbody').html(htmls);
        $("#submitUser").removeClass('desabled');
    });

    // Add Data
    $('#submitCustomer').on('click', function () {
        var values = $("#addCustomer").serializeArray();
        var name = values[0].value;
        var email = values[1].value;
        var userID = lastIndex + 1;

        console.log(values);

        firebase.database().ref('customers/' + userID).set({
            name: name,
            email: email,
        });

        // Reassign lastID value
        lastIndex = userID;
        $("#addCustomer input").val("");
    });

    // Update Data
    var updateID = 0;
    $('body').on('click', '.updateData', function () {
        updateID = $(this).attr('data-id');
        firebase.database().ref('customers/' + updateID).on('value', function (snapshot) {
            var values = snapshot.val();
            var updateData = '<div class="form-group">\
		        <label for="first_name" class="col-md-12 col-form-label">Name</label>\
		        <div class="col-md-12">\
		            <input id="first_name" type="text" class="form-control" name="name" value="' + values.name + '" required autofocus>\
		        </div>\
		    </div>\
		    <div class="form-group">\
		        <label for="last_name" class="col-md-12 col-form-label">Email</label>\
		        <div class="col-md-12">\
		            <input id="last_name" type="text" class="form-control" name="email" value="' + values.email + '" required autofocus>\
		        </div>\
		    </div>';

            $('#updateBody').html(updateData);
        });
    });

    $('.updateCustomer').on('click', function () {
        var values = $(".users-update-record-model").serializeArray();
        var postData = {
            name: values[0].value,
            email: values[1].value,
        };

        var updates = {};
        updates['/customers/' + updateID] = postData;

        firebase.database().ref().update(updates);

        $("#update-modal").modal('hide');
    });

    // Remove Data
    $("body").on('click', '.removeData', function () {
        var id = $(this).attr('data-id');
        $('body').find('.users-remove-record-model').append('<input name="id" type="hidden" value="' + id + '">');
    });

    $('.deleteRecord').on('click', function () {
        var values = $(".users-remove-record-model").serializeArray();
        var id = values[0].value;
        firebase.database().ref('customers/' + id).remove();
        $('body').find('.users-remove-record-model').find("input").remove();
        $("#remove-modal").modal('hide');
    });
    $('.remove-data-from-delete-form').click(function () {
        $('body').find('.users-remove-record-model').find("input").remove();
    });
</script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

</body>
</html>

In this file, I have created a simple CURD form using Bootstrap 4. At the end of the file, you will get the Firebase JavaScript CURD code. It’s easy to understand.

Step 6 : Run and Test

Run the laravel project by typing:

php artisan serve

Now visit the route(http://localhost:8000/customers) to see the form. You can start testing by adding data.

Here’s the Firebase database’s screenshot:

We have successfully created and tested Firebase RealTime CRUD project. You can download this project from Gitub.

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

12 Replies to “Laravel RealTime CRUD Using Google Firebase”

  1. Very helpful!! Thank you very much 😊
    I am trying to create another table by modifying this code, but the data won’t submit in firebase.
    Is it cause this code is made for one table?
    Do I need to do any command?

    1. Hello Mira,

      You’re able to define new a table like: firebase.database().ref('your-table-name/'). You can replace table customers with your table name. No need to run any extra command.

      Thanks.

      1. Thank you very much!! It works ^^

        I’m trying to make it non-empty field for the input but it doesn’t seem to work.
        Would be grateful if you can help me πŸ™‚

        1. Hi Mira, Nice to hear that πŸ™‚

          You can set validation in many ways. An example:

          // add customer
          var name = values[0].value;
          var email = values[1].value;

          if( !name || !email ) {
          console.log("Please enter name & email.");
          }

          You can check this link http://tiny.cc/0fkgqz to see more validations.

  2. Hi! How do I add validation, or alert message for this code? (Data successfully inserted etc).
    My code does not work when I tried this πŸ™
    Thank you in advance for your help!

Leave a Reply

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