CREATE WEB PUSH NOTIFICATIONS USING LARAVEL AND FIREBASE CLOUD MESSAGING. (PART 1 ).

Omar Zain
Omar Zain
Apr 20 · 5 min read

In many modern web applications, You need to implement real-time, live-updating user interfaces.

When some data is updated on the server, a message is typically sent over a connection to be handled by the client. So you need a real-time channel or WebSocket connection to handle this

Some Laravel Developers uses Pusher to handle this problem,

but Now we are going to use Firebase cloud messaging.

NOTE :

The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites.

1- Create a Laravel project and create a project on firebase.

The main idea is in two steps, First Set up a JavaScript Firebase Cloud Messaging client app to register the tokens of Firebase in Javascript and store them in the Database.

Second, you can retrieve them when you need and use them to send or receive web (push) notifications to these devices when an event or something is happening.

At first, install a fresh Laravel project >= 5.4

then, go to https://console.firebase.google.com/ and add a new project, then add the project name then click on Create project,

click on add Firebase to your web app. after that :

  • copy this configuration (Your own configurations of course).

2- Request permission for push notification and get token

Now, You’ll need to add a web app manifest that specifies the gcm_sender_id, a hard-coded value indicating that FCM is authorized to send messages to this app.

The web app manifest is a simple JSON file that tells the browser about your web application and how it should behave when ‘installed’ on the user’s mobile device or desktop.

  • Now in public directory, create manifest.json configuration file, then add gcm_sender_id which you will find it in pervious configuarations
{
"gcm_sender_id": "103953800507"
}
  • go back to your master (blade) file, add the link to this manifest file

<link rel="manifest" href="{{request()->root()}}/public/manifest.json">

after the code of initializing firebase config in the master blade,

  • add this code
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});

The method messaging.requestPermission() is responsible for showing popup of required permission to receive notifications, If permission is denied, FCM registration token requests result in an error.

  • save this code then go to your browser and refresh the page and you will see the popup of notifications.

if you clicked on Block you will see this error message, and the user won’t be able to receive notifications.

Now, we need to retrieve the current registration token, we will call getToken methiod this function returns null when permission has not been granted. Otherwise, it returns a token or rejects the promise due to an error.

* Very Important …

first, create an empty file with a name firebase-messaging-sw.js and place it in the root of your domain (Public Directory )before retrieving a token. You can add meaningful content to the file later in the client setup process.

  • also in the master blade, call the function getToken and put this code after the previous one.
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}

this code calls a getToken function ( if the token is guaranteed ) then print it in the console log to see it, else console an error.

Note: we will replace ( console.log ) with other function that saves the device token into our database.

Now, when you click Allow notification, you will see the token right now,


Now we managed to initialize Firebase configurations in our Laravel Project and Requested permission of Web Notification , then generating FCM token .

in the second part we will save this token in the database and learn how to send and receive push notifications throw firebase cloud messaging service.