In this chapter, we will create a Laravel project and connect it with the Cloud Firestore with installing all necessary packages and build some basic queries.
Step 1: Install a fresh Laravel Project with name my-project
Step 2: Setup a Firebase account and Cloud Firestore Database
A detail chapter on this topic is available here https://laravelwithfirebase.blogspot.com/2020/02/chapter-3-creating-project-in-firebase-for-laravel-php.html
Step 3: Use the Laravel package built over Firebase PHP Admin SDK by Kreait
The package url on Github: https://github.com/kreait/laravel-firebase. We have already explain the Firebase PHP Admin SDK in previous chapters by the same Author. So this code has been used by lot of people and is highly maintainable. Run the following command to install the package.
Step 1: Install a fresh Laravel Project with name my-project
composer create-project --prefer-dist laravel/laravel my-project
Step 2: Setup a Firebase account and Cloud Firestore Database
A detail chapter on this topic is available here https://laravelwithfirebase.blogspot.com/2020/02/chapter-3-creating-project-in-firebase-for-laravel-php.html
Step 3: Use the Laravel package built over Firebase PHP Admin SDK by Kreait
The package url on Github: https://github.com/kreait/laravel-firebase. We have already explain the Firebase PHP Admin SDK in previous chapters by the same Author. So this code has been used by lot of people and is highly maintainable. Run the following command to install the package.
composer require kreait/laravel-firebase
To publish this service in Laravel, run following command:
php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config
Step 4: Setting up the Firebase Credentials
Place the credentials json file obtained from Step 2 in the root of Laravel project and rename to "firebase-credentials.json".
Then update the key FIREBASE_CREDENTIALS value in config/firebase.php to the "base_path('firebase-credentials.json')"
Step 5: Installing google cloud firestore php package
composer require google/cloud-firestore
This package require grpc php extension. We will have a separate chapter to install this extension. Let us know in comment section if you face any difficulty.
Here we are ready. Our Firebase has been connected to Laravel Project.
Step 6: Create a controller name FirebaseController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FirebaseController extends Controller
{
protected $db;
public function __construct() {
$this->db = app('firebase.firestore')->database();
}
}
So $this->db is the root for your firestore and all your futher queries will take place from here.
Let us consider the following Firestore database
Following is the code to fetch the blogs from firestore
public function index(Request $request)
{
$docRef = $this->db->collection('blogs');
$query = $docRef;
if(isset($request->search))
$query = $docRef->where('name', '=', $request->search);
$documents = $query->documents();
foreach ($documents as $document) {
if ($document->exists()) {
printf('Document data for document %s:' . PHP_EOL, $document->id());
printf($document->data());
printf(PHP_EOL);
} else {
printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
}
}
}
This is the query is to fetch blogs collection and search by name inside the blogs. Then looping the documents and checking each document exists by "$document->exists()" and printing the id by "$document->id()" ex: 7PWSpBaBMTbsuEcG95P0 and the data can be fetch by "$document->data()" and to fetch name, you can retrieve by key "$document->data()['name']".
Hope now your clear with basic connection and query. Further detail query will covered in upcoming chapters. Let us know if you have any doubt in this chapter in the comments below.
29 Comments
Let us know your doubts here.
ReplyDeletephp artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config
ReplyDeleteThis one above is not working for me. I'm getting this error:
"Unable to locate publishable resources.
Publishing complete."
I tried adding this line below in config/app
'providers' => [
// ...
Kreait\Laravel\Firebase\ServiceProvider::class
]
But is getting this error instead:
"In ProviderRepository.php line 208:
Class 'Kreait\Laravel\Firebase\ServiceProvider' not found "
Tried composer update -noscript option to no avail. Anyone here getting the same error?
Thanks
This has been fixed already, someone in Github tried it and worked for him so I tried it on another project and it worked. Just a weird one I guess or I must have messed up somewhere else :)
DeleteNice to know this. Thanks
DeleteI am getting an error: firebase.firestore does not exist. Is there another way of testing if the connection is successful between the Laravel project and Firebase? Something that could probably be run in Artisan Tinker perhaps?
ReplyDeleteAfter installing the firebase package. You have to install cloud firestore also as mentioned above
Deletecomposer require google/cloud-firestore
php grpc extension is must for this
Then anywhere in controller, you have to just use
app('firebase.firestore')->database();
Thats all.
Hi, if your issue is solved by any other method than the mentioned one please share here, so other people can be benefitted.
DeleteAnd Please follow us, it helps us.
Hi. I have an error. Here it is :
ReplyDeleteKreait\Firebase\Exception\InvalidArgumentException
Invalid service account specification
Hi, the cause of this error is due to missing credential json file. Please download admin private key json file from firebase console. Place in the proper position mentioned in blog. And always check the path.
DeleteHi, if your issue is solved by any other method than the mentioned one please share here, so other people can be benefitted.
DeleteAnd Please follow us, it helps us.
During the installation of google/cloud-firestore, I had this error but the installation ended well anyway.
ReplyDeletegrpc/grpc suggests installing ext-protobuf (For better performance, install the protobuf C extension.)
google/cloud-firestore suggests installing ext-protobuf (Provides a significant increase in throughput over the pure PHP protobuf implementation. See https://cloud.google.com/php/grpc for installation instructions.)
Writing lock file
Generating optimized autoload files
Deprecation Notice: Class Grpc\Gcp\AffinityConfig located in E:/Mobiles/restaurantApp/my-project/vendor/google/grpc-gcp/src\generated\Grpc\Gcp\AffinityConfig.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Deprecation Notice: Class Grpc\Gcp\AffinityConfig_Command located in E:/Mobiles/restaurantApp/my-project/vendor/google/grpc-gcp/src\generated\Grpc\Gcp\AffinityConfig_Command.php does not comply with psr-4 autoloading standard. It will not autoload
anymore in Composer v2.0. in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Deprecation Notice: Class Grpc\Gcp\ApiConfig located in E:/Mobiles/restaurantApp/my-project/vendor/google/grpc-gcp/src\generated\Grpc\Gcp\ApiConfig.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0.
in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Deprecation Notice: Class Grpc\Gcp\ChannelPoolConfig located in E:/Mobiles/restaurantApp/my-project/vendor/google/grpc-gcp/src\generated\Grpc\Gcp\ChannelPoolConfig.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Deprecation Notice: Class Grpc\Gcp\MethodConfig located in E:/Mobiles/restaurantApp/my-project/vendor/google/grpc-gcp/src\generated\Grpc\Gcp\MethodConfig.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer
v2.0. in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Deprecation Notice: Class GPBMetadata\Google\ApiCore\Tests\Unit\Example located in E:/Mobiles/restaurantApp/my-project/vendor/google/gax/metadata\Google\ApiCore\Tests\Unit\Example.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
Please follow this article in detail https://cloud.google.com/php/grpc
Deleteand for you, we will update this article for linux pcs https://laravelwithfirebase.blogspot.com/2020/02/chapter-7-install-grpc-for-php-extension-in-windows-and-linux-ubuntu.html
Hi, if your issue is solved by any other method than the mentioned one please share here, so other people can be benefitted.
DeleteAnd Please follow us, it helps us.
Here's where the code doesn't work
ReplyDelete$this->db = app('firebase.firestore')->database();
$docRef = $this->db->collection('blogs');
$query = $docRef;
$documents = $query->documents();
So when I want to recover the data I have this error
GuzzleHttp\Exception\RequestException
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
I do not know how to do
This issue generally comes, when your server cannot connect to Firebase. Please check you have proper internet connection. And if internet is proper, please check if your local apache setup is allowed through PC's firewall.
DeleteHi if your issue is solved by any other method that can be shared here, so other people can be benefitted.
DeletePlease follow us.
how to update key FIREBASE_CREDENTIALS value in config/firebase.php to the "base_path('firebase-credentials.json')" , can i replace with this ('file' => env('FIREBASE_CREDENTIALS'), in credentials
ReplyDeleteYes anything is fine.
Delete'credentials' => [
'file' => base_path('firebase-credentials.json')
],
Do this, so base_path is accessible in config files and not in env. And 'firebase-credentials.json' file in root folder of project. This is best practice.
Hi if your issue is solved by any other method that can be shared here, so other people can be benefitted.
DeletePlease follow us.
"Unable to create a FirestoreClient: The requested client requires the gRPC extension." this occur
ReplyDeleteYes gRPC extension is must for Firestore. Please see this chapter in detail, how to install grpc https://laravelwithfirebase.blogspot.com/2020/02/chapter-7-install-grpc-for-php-extension-in-windows-and-linux-ubuntu.html
DeleteHi, if your issue is solved by any other method than the mentioned one please share here, so other people can be benefitted.
DeletePlease follow us.
Hello Users, from many subscribers requesting chapter on "gcp firebase" , we will soon be adding a detail described chapter on this. Thanks.
ReplyDelete"Return value of Kreait\Laravel\Firebase\FirebaseProjectManager::getDefaultProject() must be of the type string, null returned". this problem i am facing.
ReplyDeleteThis error generally comes of json file you got from firebase is not proper or the file path provided is not proper.
Deleteplease, share how to slove
DeleteHi Htun, the issue would be json file not readable by code. This issue generally happens relative path or full path of file. Try to debug in this way, what's the path you are getting.
DeleteAnd Htun, we would request you to please follow this blog. It really keeps us motivate to build such blogs😊
Unable to create a FirestoreClient: Error rendering 'projects/{project=*}/databases/{database=*}': expected binding 'project' to match segment '{project=*}', instead got null Provided bindings: Array ( [project] => [database] => (default) )
ReplyDeletewho can i solve this proplem
Thanks for reaching out us.
DeleteThis issue seams you have modify your admin SDK private json.