Firebase Cloud Messaging (FCM) is a powerful tool for sending push notifications to your users. In this blog post, we’ll walk through the steps to integrate Firebase push notifications into your Laravel application using the Kreait Laravel Firebase package. This will allow you to send notifications seamlessly from your Laravel backend.
Steps to Integrate Firebase Push Notifications
Step 1: Install the Kreait Firebase Package
First, we need to install the Kreait Laravel Firebase package via Composer. This package provides a convenient way to interact with Firebase services in your Laravel project.
composer require kreait/laravel-firebase
Step 2: Publish the Configuration (Optional)
To customize the Firebase settings, you can publish the configuration file. This step is optional but recommended for more advanced configurations.
php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config
This will create a config/firebase.php file in your Laravel project, which you can customize as needed.
Step 3: Add Firebase Service Account to Your Project
Download the serviceAccountKey.json file from the Firebase Console:
- Go to Firebase Console: Navigate to your Firebase project.
- Project Settings: Click the gear icon (⚙️) next to Project Overview and select Project Settings.
- Go to Service Accounts Tab: Click on the Service Accounts tab.
- a New Private Key: Click the Generate New Private Key button and download the JSON file.
Place the serviceAccountKey.json file in a secure directory, such as storage/app/firebase/serviceAccountKey.json.
Step 4: Set Up the Firebase Credentials in the .env File
Update your .env file to include the path to your Firebase service account credentials:
FIREBASE_CREDENTIALS=/full/path/to/storage/app/firebase/serviceAccountKey.json
Replace /full/path/to/ with the actual path where your serviceAccountKey.json is located.
Step 5: Configure Firebase in config/firebase.php (If published)
If you published the configuration file, update config/firebase.php to use the credentials path from your .env file:
return [
'credentials' => [
'file' => env('FIREBASE_CREDENTIALS'),
],
];
Step 6: Using Firebase Services in Laravel
Now you can use Firebase services such as Cloud Messaging to send push notifications. Here’s an example of how to set up a controller to send notifications:
Create a Controller for Sending Notifications:
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
class NotificationController extends Controller
{
public function sendNotification(Request $request)
{
// Initialize Firebase with service account credentials
$firebase = (new Factory)->withServiceAccount(env('FIREBASE_CREDENTIALS'));
// Get Firebase Messaging instance
$messaging = $firebase->createMessaging();
// Get the device token from the request
$deviceToken = $request->input('device_token');
// Ensure the device token is valid
if (empty($deviceToken)) {
return response()->json(['error' => 'Device token is missing'], 400);
}
// Create the notification
$notification = Notification::create('Test Title', 'Test Body');
// Build the message
$message = CloudMessage::withTarget('token', $deviceToken)->withNotification($notification);
try {
// Send the notification
$messaging->send($message);
return response()->json(['message' => 'Notification sent successfully']);
} catch (\Kreait\Firebase\Exception\Messaging\InvalidMessage $e) {
return response()->json(['error' => 'Invalid message: ' . $e->getMessage()], 400);
} catch (\Exception $e) {
return response()->json(['error' => 'Error sending notification: ' . $e->getMessage()], 500);
}
}
}
Step 7: Set Up a Route for Sending Notifications
In your routes/web.php or routes/api.php file, add a route for sending notifications:
Route::post('/send-notification', [NotificationController::class, 'sendNotification']);
Step 8: Test the Notification
You can test the push notification by making a POST request to /send-notification with a valid device_token in the request body. Use tools like Postman or curl:
curl -X POST http://your-domain.com/send-notification \
-H "Content-Type: application/json" \
-d '{"device_token": "your-device-token"}'
Summary
1. Install: Use Composer to install the kreait/laravel-firebase package.
2. Configure: Place the serviceAccountKey.json file securely and update your .env file.
3. Use: Implement Firebase services such as Cloud Messaging in your Laravel application.
By following these steps, you can successfully integrate Firebase push notifications into your Laravel application and start sending notifications to your users.