How to auto increment a Cloud Firestore document existing number field id #9

Learn How to auto increment a Cloud Firestore document existing number field id. In this chapter, we will learn how to insert a data with an auto increment id and using it an unique id instead of default Push ID provided by Firebase.

Consider the following example: You have a Student collection and it has data with auto incremented value. When you insert the next, it should have id = 4. Now Firebase doesnot provide anything related to this autoincrement feature. It has only unique id generated by its logic. So we will do some manual coding for it.



Now, you have the easy solution is to get the total size of the list of documents +1. Consider the following code

 $newid = app('firebase.firestore')->database()->collection('Student')  
               ->documents()->size()+$i;  
 //Insert new record  
 app('firebase.firestore')->database()->collection('Student')  
               ->document($newid)->set(['id'=> $newid, 'name' => 'Jim Perry']);  


This code has an issue if your data in between gets deleted. So the above solution will not work. Now to overcome this, we will get the last id of documents of collection and increment that by 1. For this, we will use sortby id in descending order and limiting the data to 1. Consider the following code.

Firebase preview


Now code this in laravel

 $documents = app('firebase.firestore')->database()->collection('Student')  
               ->orderby('id','desc')->limit(1)->documents();  
 if($documents->size() > 0) {  
    $lastid = intval($documents->rows()[0]->data()['id']);  
 }  
 //Insert new record  
 app('firebase.firestore')->database()->collection('Student')  
               ->document($lastid)->set(['id'=> $lastid, 'name' => 'Jim Perry']);  


But always check before insert, if you have much code in between fetch and insert. You can try five times if you feel there are muliple request at the same times

 $i = 1;  
 do {  
    $newid = $lastid+$i;  
    $doc = app('firebase.firestore')->database()->collection('Student')  
                ->where('id', '==', $newid)->documents();  
    if($doc->size() <= 0){  
     break;  
    }  
    $i++;  
   } while ($i < 5);  
Now inserted data in the firebase will be as following



Hope you are clear that how can you easily implement the auto increment id in the Firebase insertion and not using the default push id (unique ids) generated by default by Firebase.

Post a Comment

6 Comments