Throughout this comprehensive Laravel Firebase Push Notification Example; In this tutorial we are going to share we will explain how to send web push notifications in the Laravel app using Firebase Cloud Messaging mechanism. The step by step guid for firebase push notification can be implemented ini laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 apps. Send real time notification to user in laravel application using firebase.
A push notification is a message that appears on a mobile device and a web app. Push notifications provide a great way to communicate with customers or users regarding any context.
Firebase provides a realtime database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase’s cloud.
firebase push notification is a free open source and you can easily implement using your google account. here i will give you simple to getting device token of logged in users and then we will send web push notification.
To create a push notification, we need to acquire the server key or token from the firebase dashboard and add this token into the laravel app to send web push notifications. Lets see how to easily send web push notifications from the Laravel 8 app using Firebase.
How to Send Web Push Notifications in Laravel 9 using Firebase
- Create Laravel Project
- Database Connection
- Install Laravel Auth Scaffolding
- Update FCM Token to Users Table
- Get Firebase Cloud Messaging Server Key
- Create Controller
- Create Routes
- Set Up Blade View
- Create Firebase (FCM) File
- Run Laravel App
Step 1: Create Laravel Project
First run the following command in terminal to install laravel fresh app for send web notification in laravel application;
composer create-project --prefer-dist laravel/laravel laravel-web-notification
Get into the app’s root:
cd laravel-web-notification
Step 2: Database Connectivity
Update your add database name, username and password in the .env file for database connectivity:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Step 3: Create Laravel Auth using scaffold
Next, we have to install the laravel ui package and create auth scaffolding using the following commands.
composer require laravel/ui
Run the following command to manifest bootstrap auth ui.
php artisan ui bootstrap --auth
After that wWe need to run suggested commands to compile your fresh scaffolding.
npm install && npm run dev
Step 4: Create Migration and Update Model
Here we need to add the new column in the current users table inside the database, execute the below command.
php artisan make:migration add_fcm_token_to_users_table
database/migrations/2022_01_23_144523_add_fcm_token_to_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddFcmTokenToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('fcm_token')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('fcm_token');
});
}
}
Head over to the terminal, type the following command, and execute it to run the migration.
php artisan migrate
Now add the fcm_token to fillable property.
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'fcm_token',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step 5: Get Firebase Cloud Messaging (FCM) Server Key
This step will describe how to get the Firebase cloud messaging server key and Firebase web app’s configuration credentials.
So, first go to Firebase site and here you need to create a Firebase project.
Then, add the notification app name for adding Firebase to your web app.
Copy the Firebase configuration keys, and this will help to connect laravel to Firebase.
Get into the Firebase project dashboard in the “Settings” page, click on the “Cloud Messaging” tab. You need to look for the “Server key”, copy this cloud messaging server key, and you have to paste this key in your env file.
FCM_SERVER_KEY=XXXXX //server key here
Step 6: Create Controller
We need to create some functions in the controller file to handle web notifications, so first generate the controller.
php artisan make:controller NotificationController
app\Http\Controllers\NotificationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class NotificationController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('home');
}
public function storeToken(Request $request)
{
auth()->user()->update(['fcm_token'=>$request->token]);
return response()->json(['Token successfully stored.']);
}
public function sendNotification(Request $request)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$FcmToken = User::whereNotNull('fcm_token')->pluck('fcm_token')->all();
$serverKey = env('FCM_SERVER_KEY');
$data = [
"registration_ids" => $FcmToken,
"notification" => [
"title" => $request->title,
"body" => $request->body,
]
];
$encodedData = json_encode($data);
$headers = [
'Authorization:key=' . $serverKey,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
// FCM response
dd($result);
}
}
Step 7: Create Routes
Now import NotificationController controller to your web.php file and update the routes.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NotificationController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Auth::routes();
Route::get('/push-notificaiton', [NotificationController::class, 'index'])->name('push-notificaiton');
Route::post('/store-token', [NotificationController::class, 'storeToken'])->name('store.token');
Route::post('/send-notification', [NotificationController::class, 'sendNotification'])->name('send.notification');
Step 8: Create Blade Files
In this step update the home blade file, integrate push notification code for the web app, So, replace the home blade file code with the following code.
resources/views/home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<button onclick="startFCM()"
class="btn btn-danger btn-flat">Allow notification
</button>
<div class="card mt-3">
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
<form action="{{ route('send.web-notification') }}" method="POST">
@csrf
<div class="form-group">
<label>Message Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label>Message Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<button type="submit" class="btn btn-success btn-block">Send Notification</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.3.2/firebase.js"></script>
<script>
var firebaseConfig = {
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
function startFCM() {
messaging
.requestPermission()
.then(function () {
return messaging.getToken()
})
.then(function (response) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route("store.token") }}',
type: 'POST',
data: {
token: response
},
dataType: 'JSON',
success: function (response) {
alert('Token stored.');
},
error: function (error) {
alert(error);
},
});
}).catch(function (error) {
alert(error);
});
}
messaging.onMessage(function (payload) {
const title = payload.notification.title;
const options = {
body: payload.notification.body,
icon: payload.notification.icon,
};
new Notification(title, options);
});
</script>
@endsection
Step 9: Create Firebase (FCM) File
No we have to create head over to a public folder and create a new firebase-messaging-sw.js file; this file holds the web push notification configurations.
So, after creating the file, add the given below code in the public/firebase-messaging-sw.js file.
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
*/
firebase.initializeApp({
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log("Message received.", payload);
const title = "Hello world is awesome";
const options = {
body: "Your notificaiton message .",
icon: "/firebase-logo.png",
};
return self.registration.showNotification(
title,
options,
);
});
Laravel Send Web Push Notification using Firebase Tutorial
Finally, we have to buid the push notification in Laravel using FCM, Now we need to run our project using the serve command to start the laravel development server.
php artisan serve
After, you signed-in, hitt following url in your browser:
http://127.0.0.1:8000/push-notificaiton
Next, you need to click on the allow notification button, it will generate the device id, also add push notification title and body in the given form.
you will receive notification as like bellow:
I hope this laravel push notification using firebase work for you.