RealTime CRUD operation Using Google Firebase in Laravel 5.6

Generic placeholder image
Brijpal Sharma
php laravel  

Date:-November 10th, 2018 , Posted On:- Web Development


Today our topic is how to perform in realtime CRUD operation using google firebase in Laravel 5.6

Today we learn on CoderMen how to perform CRUD operation using google firebase in Laravel 5.6. real-time create, read, updates and delete or destroy this all thing possible with using google firebase database. in this post, we show you step by step this application.

The best thing about google firebase we can perform much stuff by google firebase. after following this all step of this post, then you will get final output look like the following screenshot.

Step:1 Create a new google firebase project

Before we start this project first we need to create a new google firebase project. to create a new project click on this link. google firebase 

RealTime CRUD operation Using Google Firebase in Laravel 5.6

After clicking on Add Project you will see

RealTime CRUD operation Using Google Firebase in Laravel 5.6

Give a good name of your project and accept Terms and condition click on create a project button.

RealTime CRUD operation Using Google Firebase in Laravel 5.6

After that, you will see this dashboard

RealTime CRUD operation Using Google Firebase in Laravel 5.6

After selecting your project environment then you can see one popup and in this popup, you can get your apiKeyauthDomaindatabase URL.

RealTime CRUD operation Using Google Firebase in Laravel 5.6

Now, we created google firebase project successfully for RealTime CRUD operation Using Google Firebase in Laravel 5.6 in your google firebase console. so we can manage all this setting regarding our firebase project. like create a new database, manage notification.

Now we have following details

1.) api_key

2.) auth_domain

3.) database_url

4.) secret

5.) Legacy server key (use for notification)

Step:2 Create a new Laravel project

Create a new Laravel Project using this command

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

After create successfully project open config\Service.php and add this flowing code details.

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

Create Route   Routes\web.php

Route::get('users', 'HomeController@users');

This route will use to show user details when we perform CRUD operation.

And now Crate a new HomeController using this flowing command.

php artisan make:controller HomeController

After that go the new HomeController and create a new functions users

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function users()
    {
        return view('userdetails');
    }
}

In this function, we return on a view userdetails.blade.php so we need to create a view. userdetails.blade.php and add this flowing code.

@extends('layouts.app')

@section('style')
<style type="text/css">
.desabled {
	pointer-events: none;
}
</style>
@endsection

@section('content')
<div class="container">
    <div class="row">
    	<div class="col-md-4">
    		<div class="card card-default">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <strong>Add User</strong>
                        </div>
                    </div>
                </div>

                <div class="card-body">
                    <form id="addUser" class="" method="POST" action="">
                    	<div class="form-group">
                            <label for="first_name" class="col-md-12 col-form-label">First Name</label>

                            <div class="col-md-12">
                                <input id="first_name" type="text" class="form-control" name="first_name" value="" required autofocus>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="last_name" class="col-md-12 col-form-label">Last Name</label>

                            <div class="col-md-12">
                                <input id="last_name" type="text" class="form-control" name="last_name" value="" required autofocus>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-12 col-md-offset-3">
                                <button type="button" class="btn btn-primary btn-block desabled" id="submitUser">
                                    Submit
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
    	</div>
        <div class="col-md-8">
            <div class="card card-default">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <strong>All Users Listing</strong>
                        </div>
                    </div>
                </div>

                <div class="card-body">
                    <table class="table table-bordered">
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th width="180" class="text-center">Action</th>
                        </tr>
                        <tbody id="tbody">
                        	
                        </tbody>	
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Model -->
<form action="" method="POST" class="users-remove-record-model">
    <div id="remove-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;">
        <div class="modal-dialog" style="width:55%;">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="custom-width-modalLabel">Delete Record</h4>
                    <button type="button" class="close remove-data-from-delete-form" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <h4>You Want You Sure Delete This Record?</h4>
                </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 deleteMatchRecord">Delete</button>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- Update Model -->
<form action="" method="POST" class="users-update-record-model form-horizontal">
    <div id="update-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;">
        <div class="modal-dialog" style="width:55%;">
            <div class="modal-content" style="overflow: hidden;">
                <div class="modal-header">
                    <h4 class="modal-title" id="custom-width-modalLabel">Update Record</h4>
                    <button type="button" class="close update-data-from-delete-form" 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-default waves-effect update-data-from-delete-form" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success waves-effect waves-light updateUserRecord">Update</button>
                </div>
            </div>
        </div>
    </div>
</form>
@endsection

 

After adding this structure in HTML code we need to add some JavaScript code to perform realTime CRUD operation for our Application.

<script src="https://www.gstatic.com/firebasejs/4.9.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('users/').on('value', function(snapshot) {
    var value = snapshot.val();
    var htmls = [];
    $.each(value, function(index, value){
    	if(value) {
    		htmls.push('<tr>\
        		<td>'+ value.first_name +'</td>\
        		<td>'+ value.last_name +'</td>\
        		<td><a data-toggle="modal" data-target="#update-modal" class="btn btn-outline-success updateData" data-id="'+index+'">Update</a>\
        		<a data-toggle="modal" data-target="#remove-modal" class="btn btn-outline-danger removeData" data-id="'+index+'">Delete</a></td>\
        	</tr>');
    	}    	
    	lastIndex = index;
    });
    $('#tbody').html(htmls);
    $("#submitUser").removeClass('desabled');
});


// Add Data
$('#submitUser').on('click', function(){
	var values = $("#addUser").serializeArray();
	var first_name = values[0].value;
	var last_name = values[1].value;
	var userID = lastIndex+1;

    firebase.database().ref('users/' + userID).set({
        first_name: first_name,
        last_name: last_name,
    });

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

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

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

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

	var updates = {};
	updates['/users/' + 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 +'">');
});

$('.deleteMatchRecord').on('click', function(){
	var values = $(".users-remove-record-model").serializeArray();
	var id = values[0].value;
	firebase.database().ref('users/' + 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>

After adding this code of in our blade page then your realtime crud system done successfully completed.

Now we are ready to use our example so run below command.

php artisan serve

After that go to this URL.

http://localhost:8000/users

So finally we completed RealTime CRUD operation Using Google Firebase in Laravel 5.6 

 


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

1 comments
Generic placeholder image
Akash garg
December 27th, 2018 - 12:58AM

It's Working

You must be logged in to post a comment.