Want to send push notification in Android from Laravel backend? This detailed guide will surely help you with that.
Push notifications have become a crucial element in modern applications, enhancing user engagement and providing real-time updates.
In this comprehensive guide, we’ll explore how you can send push notifications from a Laravel backend to Android devices using Firebase Cloud Messaging (FCM).
This integration allows for seamless communication between your Laravel application and Android clients.
That said, you can follow these simple steps to send push notification in Android from Laravel backend –
Step #1: Setup Laravel Project
The first step is to set up your Laravel project if you haven’t already. You can create a new project using Composer:
composer create-project --prefer-dist laravel/laravel your_project_name
Step #2: Install Laravel Breeze
Laravel Breeze simplifies the process of adding authentication scaffolding to your project.
You can install Breeze with the following commands:
composer require laravel/breeze --dev
php artisan breeze:install react
npm install && npm run dev
Step #3: Integrate Firebase
Firebase will serve as the bridge between your Laravel backend and Android devices.
Follow these steps to integrate Firebase:
- Install the kreait/laravel-firebase package.
- Publish the Firebase configuration file.
php artisan vendor:publish --provider="Kreait\Laravel\Firebase\ServiceProvider" --tag=config
- Create a Firebase project in the Firebase Console and download the JSON file containing your credentials. Place this file at the root of your Laravel project.
- Update the config/firebase.php file to specify the location of your Firebase credentials JSON file.
Step #4: Modify User Table
Add a column to the users table to store the FCM token assigned by Firebase:
php artisan make:migration add_fcm_device_token_column_to_users_table --table=users
Update the generated migration file to add the ‘fcm_token’ column:
// database/migrations/xxxx_xx_xx_add_fcm_device_token_column_to_users_table.php
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('fcm_token')->nullable()->after('password');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('fcm_token');
});
}
After that, run the migration to apply the changes. You can do so by executing this command:
php artisan migrate
Step #5: Setup Android Client
For Android clients, integrate the Firebase SDK into your Android project. This involves adding the necessary dependencies and initializing Firebase in your Android application. Refer to the official Firebase documentation for detailed instructions.
Step #6: Handle Device Registration
Next, we need to handle device registrations in Laravel. For this, create a controller to handle device token registration.
php artisan make:controller FirebasePushController
In the controller, initialize the Firebase Cloud Messaging Service and create a method to register the device token. You can follow the below shared code for the same –
// app/Http/Controllers/FirebasePushController.php
use Kreait\Laravel\Firebase\Facades\Firebase;
protected $notification;
public function __construct()
{
$this->notification = Firebase::messaging();
}
public function setToken(Request $request)
{
$token = $request->input('fcm_token');
$request->user()->update([
'fcm_token' => $token
]);
return response()->json([
'message' => 'Successfully Updated FCM Token'
]);
}
Next, define a route for handling the device token registration:
// routes/api.php
Route::post('setToken', [FirebasePushController::class, 'setToken'])->name('firebase.token');
Step #7: Retrive and Send Device Token
In your Android application, initialize the Firebase SDK and retrieve the device token. You can have a look at the following code for example:
// Code snippet in Android (Java/Kotlin)
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null) {
String fcmToken = task.getResult();
// Send the token to your Laravel backend
sendTokenToServer(fcmToken);
}
});
After that, implement the sendTokenToServer method to send the obtained token to your Laravel backend.
Step #8: Send Push Notifications from Laravel
Lastly, create a method in the FirebasePushController to send push notifications. You can have a look at the below-shared code, for example –
// app/Http/Controllers/FirebasePushController.php
use Kreait\Firebase\Messaging\CloudMessage;
public function notification(Request $request)
{
$fcmToken = auth()->user()->fcm_token;
$title = $request->input('title');
$body = $request->input('body');
$message = CloudMessage::fromArray([
'token' => $fcmToken,
'notification' => [
'title' => $title,
'body' => $body
],
]);
$this->notification->send($message);
}
Here, define a route for sending push notifications:
// routes/api.php
Route::post('send/notification', [FirebasePushController::class, 'notification'])->name('firebase.send');
Step #9: Testing
Now that you have configured everything, it is time for you to test it for the end-to-end flow. You can do that by sending push notification in Android from Laravel backend.
Conclusion
Sending push notifications from a Laravel backend to Android devices involves integrating Firebase Cloud Messaging and handling device tokens.
This guide covers each step, from Laravel project setup to Android client integration, ensuring a seamless communication channel between your backend and Android applications.
That’s it for this blog. We will be coming up with more such content soon to ensure you never every get stuck with your notification problems.
Meanwhile, we have covered guides on implementing push notifications using HTML5 & JavaScript, React Native, as well as Django. You should definitely give them a read.