How to Integrate firebase database with laravel and save functionality
In this tutorial, we will use default firebase database so first login to google console and go to project settings -> service account adn click on generate new private key and download it and put it in root folder of laravel app
1) Install Google Cloud Firestore via Composer:
composer require google/cloud-firestore
2) Add Firebase Credentials to
.env
file:
Ensure you have added the following in your .env
file:FIREBASE_CREDENTIALS=./firebase_credentials.json
FIREBASE_PROJECT_ID=mydb
3) Create a Firestore Service Provider: You need to create a service provider to configure Firestore in your Laravel app. Run the following command to generate a service provider:
php artisan make:provider FirestoreServiceProvider
4) Configure Firestore in the Service Provider: Open the newly created
FirestoreServiceProvider.php
file and configure Firestore:<?php
namespace App\Providers;
use Google\Cloud\Firestore\FirestoreClient;
use Illuminate\Support\ServiceProvider;
class FirestoreServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->singleton(FirestoreClient::class, function ($app) {
$config = [
'projectId' => env('FIREBASE_PROJECT_ID'),
'keyFilePath' => base_path(env('FIREBASE_CREDENTIALS')),
];
return new FirestoreClient($config);
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
5) Register the Service Provider: Add the newly created service provider to the
providers
array in config/app.php
:'providers' => [
// Other service providers...
App\Providers\FirestoreServiceProvider::class,
],
6) Using Firestore in Your Application: Now you can use Firestore in your controllers or services. For example, to save data to the
inquiries
collection, you can do the following in a controller:<?php
namespace App\Http\Controllers;
use Google\Cloud\Firestore\FirestoreClient;
use Illuminate\Http\Request;
class InquiryController extends Controller
{
protected $firestore;
public function __construct(FirestoreClient $firestore)
{
$this->firestore = $firestore;
}
public function store(Request $request)
{
$data = [
'name' => $request->input('name'),
'email' => $request->input('email'),
'message' => $request->input('message'),
'created_at' => now(),
];
$this->firestore->collection('inquiries')->add($data);
return response()->json(['success' => 'Inquiry saved successfully.']);
}
}
7) Define a Route: Add a route to handle the inquiry submission in
routes/web.php
or routes/api.php
:use App\Http\Controllers\InquiryController; Route::post('/inquiries', [InquiryController::class, 'store']);
thats it ! now access the url
Comments
Post a Comment