Chapter 10 - Fetch data from Firebase performing Simple and compound queries using Laravel PHP

In this chapter, we will learn how to can fetch data from Firebase Cloud Firestore by performing simple and compound queries using Laravel PHP package.

Consider the list of Student in Firebase Cloud Firestore. We would fetch these student data using all example of queries.



Fetch the normal list


 $students = app('firebase.firestore')->database()->collection('Student')->documents();  
 print_r('Total records: '.$students->size());  
 foreach($students as $stu) {  
   if($stu->exists()){  
    print_r('Student ID = '.$stu->id());  
    print_r('Student Name = '.$stu->data()['name']);  
   }  
 }  


Now search query, search by name in student list

 $students = app('firebase.firestore')->database()->collection('Student')->documents()  
 ->where('name','==','John Doe');  
Remember there is no like query in firebase. We have to make exact match, even it is case sensitive. Example these search words would not work "John Doe" data:
"john doe", "John", "Doe", "Joh"

Using Sort Functionality, order by name in Ascending

 $students = app('firebase.firestore')->database()->collection('Student')->documents()  
 ->orderby('name','asc');  

Order by id in descending

 $students = app('firebase.firestore')->database()->collection('Student')->documents()  
 ->orderby('id','desc');  

Using limit and offset for implementing pagination

 $students = app('firebase.firestore')->database()->collection('Student')->documents()  
 ->offset(0)->limit(10);  

Now if you data get insert in your list when your fetching the list. So will use startAfter functionality. Consider this as next page token we use to get data from the last data of first request.

 $laststudent = false;  
 $morestudent = true;  
 while($morestudent) {  
   $students = app('firebase.firestore')->database()->collection('Student');  
   if($laststudent)  
      $students->startAfter($laststudent);  
   $students->limit(10)->documents();  
   print_r('Total records: '.$students->size());  
   if($students->size() > 0){  
     foreach($students as $stu) {  
       if($stu->exists()){  
         print_r('Student ID = '.$stu->id());  
         print_r('Student Name = '.$stu->data()['name']);  
       }  
     }  
   }else{  
     $morestudent = false;  
   }  
 }  

Now fetch by id detail of Student. The detail page of the student.

 app('firebase.firestore')->database()->collection('Student')->documents(<studentid>)->snapshot();  

Example
 $student = app('firebase.firestore')->database()->collection('Student')->document('defT5uT7SDu9K5RFtIdl')->snapshot();  
 print_r('Student ID = '.$student->id());  
 print_r('Student Name = '.$student->data()['name']);  


Hope the listing of data from Firebase Cloud Firestore is now clear. Please let us know in comments if you have any doubts.

Post a Comment

33 Comments

  1. Replies
    1. Sir how to show data in a table on web page after fetching the data from firestore

      Delete
    2. Hello, thanks for asking your query.

      In foreach
      foreach($students as $stu)

      You can create your array of entries data and send as json to frontend..

      Or if you are using datatable, then in that required format.

      Delete
  2. Can you please do a article where you are using Laravel Eloquent Model & Firebase

    ReplyDelete
    Replies
    1. Do you means User model connect to User collection?

      Delete
    2. hi did you already do it with laravel controller with route on web.php? Can i know about it? thanks

      Delete
    3. Hi

      Yes. Routes and controller usage remains same as usual

      Please hit follow and show your support

      Delete
    4. Followed you way before already. Anyway, thank you. Will try it later and will give you a feedback

      Delete
  3. Call to undefined method Google\Cloud\Firestore\QuerySnapshot::offset() and othet method like limit(), orderby() etc.

    is there anything to add before? please help

    ReplyDelete
    Replies
    1. Hi Kit, thanks for contacting us.

      By the seeing the error, it's seems you are quering on snapshot. Don't use snapshot(). Query is direct on

      ->collection('Student')
      and then
      ->documents ()

      Hope it helps. Please follow us.

      Delete
    2. Kur, please follow us by click Follow on sidebar. It helps us.

      Delete
    3. I already Use that but still the same error came out

      Delete
    4. Hi tiago,

      Can you share your exact query?

      Delete
  4. Good day. I'm trying to print a value of the reference data type but I keep getting this error: htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\adminltefire\resources\views\words\index.blade.php)

    ReplyDelete
    Replies
    1. Hi Tofunmi,

      Thanks for reaching out us.

      You can try using dd() instead of print_r().

      Hope it helps. Please follow us.

      Delete
    2. Actually, I have 2 collections, Users and Words.

      In the words collection, I have a field called user (with a value of: Users/0311c6ba0d194ee09747) which stores the name of the user who added a new word.

      So now, I want to display each word alongside with the name of the user who uploaded them in my blade file. (I'm using laravel)

      Delete
    3. Hi Tofunmi,

      You can call snapshot() on the reference field to fetch the data of specific user.

      Consider your foreach loop of words

      foreach($words as $w) {
      $userdata = $w->data()['user']->snapshot();
      print_r($userdata->data()['name']);
      }

      Done. Hope it helps. You can show your support to this blog, by just hitting the follow button on right top. And you can just give a try to our app (play store link below in green button) and provide feedback.

      Delete
  5. Actually, I have 2 collections, Users and Words.

    In the words collection, I have a field called user (with a value of: Users/0311c6ba0d194ee09747) which stores the name of the user who added a new word.

    So now, I want to display each word alongside with the name of the user who uploaded them in my blade file. (I'm using laravel)

    ReplyDelete
    Replies
    1. Hi Tofunmi,

      You can call snapshot() on the reference field to fetch the data of specific user.

      Consider your foreach loop of words

      foreach($words as $w) {
      $userdata = $w->data()['user']->snapshot();
      print_r($userdata->data()['name']);
      }

      Done. Hope it helps. You can show your support to this blog, by just hitting the follow button on right top. And you can just give a try to our app (play store link below in green button) and provide feedback.

      Delete
  6. Thank you for making production easy! Best Regards, keep it up.

    ReplyDelete
    Replies
    1. Thanks. We are glad it helped you.

      Please show your support to our blog, by just clicking Follow button at the top.

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hi Abhijith V S
      Thanks for reaching out us.
      This line in above post
      $students->startAfter($laststudent) is used for pagination. You can use limit and startAt or start After.

      Hope your issue is solved. Show your support by following us on top left.

      Delete
  8. How can we convert the retrieved firestore query result to JSON ?

    ReplyDelete
    Replies
    1. Hi Abhijith
      Thanks for reaching out us. Please follow us.

      For json, you can simply foreach each data and create a json object.

      Delete
  9. kindly provide full firestore laravel pagination code with controllers and View.

    ReplyDelete
    Replies
    1. $students = app('firebase.firestore')->database()->collection('Student')->documents()
      ->offset(0)->limit(10);

      This this main code of pagination. Offset means start point and limit means how much data to take.

      Hope it helps. Please share our blog.

      Delete
  10. how to fetch timestamp from firestore to laravel?

    ReplyDelete
    Replies
    1. hi, thanks for asking.

      To add a new timestamp, use this

      new \Google\Cloud\Core\Timestamp(new \DateTime())

      And to fetch a timestamp of Firebase in Laravel

      date("Y-m-d H:i:s", strtotime($stu->data()['createdon'])):

      Delete
  11. Hi! Can i run where clause on one field and orderby on another firestore document field?

    ReplyDelete
    Replies
    1. Hi Prabitra

      Can you check this chapter

      https://laravelwithfirebase.blogspot.com/2020/06/chapter-17-how-to-query-based-on-multiple-where-clause-firebase-laravel-php.html

      And please share the issue when you query where and orderby together.

      Please show your support by following this blog. Follow button at the top.

      Delete