Below are the steps to integrate Firebase with Laravel 6.x
Step 1
To integrate Firebase with Laravel we first need a Laravel project. Create a new Laravel project using the given composer command.
composer create-project --prefer-dist laravel/laravel firebase
Step 2
Goto the folder firebase and run below command.
composer require kreait/firebase-php ^4.0
Step 3
Setup firebase by signing up with Gmail account. It will bring you to the screen shown below.
Step 4
Click on the add new project and follow the below steps:
1.
2.
3.
4. Wait for the completion of the process.
5. This is how the screen looks like when process is completed.
6. Create the database under the project as shown in the screenshot.
7. Choose one of these choices as per your requirement:
8. For now we will choose test mode and will follow the steps given in screenshot:
9. Wait for the processing. After it is done, below screen will come up:
10. Now for the database integration setting please click on gear button on the top right side as shown in the screenshot.
11. Now follow the steps shown in the screenshots:
12. Click the Service Account tab shown in the Settings page.
13. Data under Service Account looks like this –
14. Note the database url shown in this screenshot as it is required for integration. Generate Private Key button will download a json file on your system, this file has the configuration details, we need to locate the service account:
Content of json file looks like this:
{
"type": "service_account",
"project_id": "project_id",
"private_key_id": "55ds6ds2dsad6d6dsad23sad3sa6d5ddsa3",
"private_key": "-----BEGIN PRIVATE KEY-----\nMJIIFDSDUFJiojNNIOKNLLKNKLNkllkknln\nKJNKJNJN++ojkkjhjkjkKLLKJKLJKLJ+kjh\nsnbjksahuddssadnkkJHSAKJDASJ02422+ADSljkj\n-----Going on this long -----\nB77tu2DPbAMN1gTdImwyYw==\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-somethinglikethis.com",
"client_id": "1231546532132165778",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-something-over-here-gserviceaccount.com"
}
This is all we need from firebase end. We’ll now turn back to laravel project.
Step 5
Open the project in a text editor that you like and then go to .env file and paste this code with all the correct information from the json as well as from settings tab on the site-
FIREBASE_DATABASE_URL=
FIREBASE_PROJECT_ID=
FIREBASE_PRIVATE_KEY_ID=
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMJIIFDSDUFJiojNNIOKNLLKNKLNkllkknln\nKJNKJNJN++ojkkjhjkjkKLLKJKLJKLJ+kjh\nsnbjksahuddssadnkkJHSAKJDASJ02422+ADSljkj\n-----Going on this long -----\nB77tu2DPbAMN1gTdImwyYw==\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=
FIREBASE_CLIENT_ID=
FIREBASE_CLIENT_x509_CERT_URL=
Step 6
Now under the app directory of the Laravel project create a new directory named Services and add a file to it(like FirebaseService.php). Paste the following code under the class.
public function __construct()
{
try {
$serviceAccount = ServiceAccount::fromArray([
"type" => "service_account",
"project_id" => config('services.firebase.project_id'),
"private_key_id" => config('services.firebase.private_key_id'),
"private_key" => config('services.firebase.private_key'),
"client_email" => config('services.firebase.client_email'),
"client_id" => config('services.firebase.client_id'),
"auth_uri" => "https://accounts.google.com/o/oauth2/auth",
"token_uri" => "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url" => "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url" => config('services.firebase.client_x509_cert_url')
]);
$this->firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri(config('services.firebase.database_url'))
->create();
$this->database = $this->firebase->getDatabase();
} catch (Exception $e) {
Log::error('Exception in __construct in ContactController --- '.$e->getMessage());
}
}
Make sure to include these namespaces-
use Exception;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Exception\Auth\EmailExists as FirebaseEmailExists;
Step 7
Run below command to add provider for registering service that we created:
php artisan make:provider FirebaseServiceProvider
Step 8
When you hit enter, FirebaseServiceProvider.php file will be created under app/Providers directory. Now, go to FirebaseServiceProvider.php file and in the file under register function, register your service. Example of the code is shown below:
<?php
namespace App\Providers;
use App\Services\FirebaseService;
use Illuminate\Support\ServiceProvider;
use App\Observers\UserFavouriteObserver;
class FirebaseServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->singleton('FirebaseService', function () {
return new FirebaseService();
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
Step 9
Do not forget to register your provider class in config/app.php file in providers array-
App\Providers\FirebaseServiceProvider::class
Step 10
Clear the cache of project using following commands:
php artisan cache:clear
php artisan config:cache
Step 11
Start the server using php artisan serve command.
Step 12
For testing purposes, create a controller using this command-
php artisan make:controller FirebaseController
Step 13
In your app/Http/Controllers/FirebaseController, paste the following code –
<?php
namespace App\Http\Controllers;
use App\Services\FirebaseService;
use Illuminate\Http\Request;
class FirebaseController extends Controller
{
private $fire;
private $database;
function __construct(FirebaseService $fire)
{
$this->fire = $fire;
$this->database = $fire->getDatabase();
}
function test(){
try {
$newPost = $this->database
->getReference('blog/posts')
->push([
'title' => 'Laravel FireBase Test' ,
'category' => 'Laravel'
]);
return $newPost->getvalue()->toJson();
} catch (\Throwable $th) {
//throw $th;
}
}
}
Step 14
Assign a route to this method in web.php as shown below-
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/firebase', 'FirebaseController@test);
Step 15
When you go to this URL: http://localhost:8000/firebase the browser will show the following output:
Step 16
Go to firebase console you will find this in your database:
Yep! you did the integration. Enjoy Coding …… 🙂