Firebase Push Notification Laravel Tutorial

Firebase Push Notification Laravel Tutorial

In this post we will give you information about Firebase Push Notification Laravel Tutorial. Hear we will give you detail about Firebase Push Notification Laravel Tutorial And how to use it also give you demo for it if it is necessary.

What is Push Notification?

Push notifications are clickable pop-up messages that appear on your user’s browsers irrespective of the device they’re using or the browser they’re on. They serve as a quick communication channel enabling companies to convey messages, offers, or other information to their customers.

What is Firebase?

Firebase is a platform developed by Google for creating mobile and web applications. It was originally an independent company founded in 2011. In 2014, Google acquired the platform and it is now their flagship offering for app development.

Firebase is a Backend-as-a-Service (Baas). It provides developers with a variety of tools and services to help them develop quality apps, grows their user base, and earn profit. It is built on Google’s infrastructure. Firebase is categorized as a NoSQL database program, which stores data in JSON-like documents.

What is Firebase Cloud Messaging (FCM)?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention.

In this article, we will walk you through an easy-to-follow tutorial on how you can enable push notifications using FCM. We will also share with you some of the small tips to take note of so you can have this up as quickly as possible.

Let’s Start with some basic steps.

Step 1: Create a Laravel Project

First, open Terminal and run the following command to create a fresh Laravel project:

composer create-project --prefer-dist laravel/laravel larafire-push

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new larafire-push

Step 2: Configure Database Detail

After, Installation Go to the project root directory, open .env file, and set database detail as follow:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

Step 3: Create Auth using scaffold

Now, in this step, we will create auth scaffold command to create a login, register, and dashboard. so run the following commands:

composer require laravel/ui

For Generate Login, Register and Dashboard run the following command:

php artisan ui bootstrap --auth
npm install && npm run dev

Step 4: Create Migration File For Add Column

In this step, We need to add one column to the user’s table for store fcm_token.

php artisan make:migration "add fcm_token column to users table"

database/migrations/2021_04_03_093425_add_fcm_token_column_to_users_table.php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class AddFcmTokenColumnToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->after('remember_token',function($table){
                $table->text('fcm_token')->nullable();
            });
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('fcm_token');
        });
    }
}

after update migration file run the following command:

php artisan migrate

app/Models/Users.php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

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',
    ];
}

Also see: Laravel Livewire Crud Tutorial

Step 5: Create Firebase Project

In this step, We have to create a project on Firebase Console and then we have to create a web app on this project as you can see in these screenshots:

1. Create Firebase Project

2. Create a Web App in created Project

3. Web App Configuration Detail

Step 6: Add Route and Update Controller

appHttpControllersHomeController.php

public function updateToken(Request $request){
    try{
        $request->user()->update(['fcm_token'=>$request->token]);
        return response()->json([
            'success'=>true
        ]);
    }catch(Exception $e){
        report($e);
        return response()->json([
            'success'=>false
        ],500);
    }
}

add a route in routes/web.php

use AppHttpControllersHomeController;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::patch('/fcm-token', [HomeController::class, 'updateToken'])->name('fcmToken');
Route::post('/send-notification',[HomeController::class,'notification'])->name('notification');

Step 7: Add Firebase Code

resources/views/layouts/app.blade.php

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
    https://firebase.google.com/docs/web/setup#available-libraries -->

<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
        apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
        authDomain: "XXXXXXX.firebaseapp.com",
        projectId: "XXXXXXXXXX",
        storageBucket: "XXXXXXXXXX.appspot.com",
        messagingSenderId: "XXXXXXXXXX",
        appId: "1:XXXXXXXXX:web:XXXXXXXXXXXXX"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);

    const messaging = firebase.messaging();

    function initFirebaseMessagingRegistration() {
        messaging.requestPermission().then(function () {
            return messaging.getToken()
        }).then(function(token) {
            
            axios.post("{{ route('fcmToken') }}",{
                _method:"PATCH",
                token
            }).then(({data})=>{
                console.log(data)
            }).catch(({response:{data}})=>{
                console.error(data)
            })

        }).catch(function (err) {
            console.log('Token Error :: ${err}');
        });
    }

    initFirebaseMessagingRegistration();
  
    messaging.onMessage(function({data:{body,title}}){
        new Notification(title, {body});
    });
</script>

Create firebase-messaging-sw.js in a public folder

importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');
   
firebase.initializeApp({
    apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXX",
    projectId: "XXXXXXXX",
    messagingSenderId: "XXXXXXXXX",
    appId: "1:XXXXXXXX:web:XXXXXXXXXXX"
});
  
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function({data:{title,body,icon}}) {
    return self.registration.showNotification(title,{body,icon});
});

Step 8: Send Push Notification

For Sending Push Notification From Laravel Project, We are using this Larafirebase Package.

Larafirebase is a package that offers you to send push notifications or custom messages via Firebase in Laravel.

Install Larafirebase Package:

composer require kutia-software-company/larafirebase

Copy Config:

php artisan vendor:publish --provider="KutiaLarafirebaseProvidersLarafirebaseServiceProvider"

Add Firebase Server Key to .env:

FIREBASE_SERVER_KEY=XXXXXXXXXXXXXXXXXXXXX

For Send Push Notification We need a firebase server key, you can get the server key from the firebase project settings as you can see in this screenshot.

Configure config/larafirebase.php

return [
    'authentication_key' => env('FIREBASE_SERVER_KEY')
];

Now, We can send notifications From the Controller as well as from the Notification class.

Example usage in Controller/Service or any class:

app/Http/Controllers/HomeController.php

public function notification(Request $request){
    $request->validate([
        'title'=>'required',
        'message'=>'required'
    ]);

    try{
        $fcmTokens = User::whereNotNull('fcm_token')->pluck('fcm_token')->toArray();

        //Notification::send(null,new SendPushNotification($request->title,$request->message,$fcmTokens));

        /* or */

        //auth()->user()->notify(new SendPushNotification($title,$message,$fcmTokens));

        /* or */

        Larafirebase::withTitle($request->title)
            ->withBody($request->message)
            ->sendMessage($fcmTokens);

        return redirect()->back()->with('success','Notification Sent Successfully!!');

    }catch(Exception $e){
        report($e);
        return redirect()->back()->with('error','Something goes wrong while sending notification.');
    }
}

Example usage in Notification class:

First Create Notification using following command:

php artisan make:notification SendPushNotification

appNotificationsSendPushNotification.php

namespace AppNotifications;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateNotificationsNotification;
use KutiaLarafirebaseMessagesFirebaseMessage;

class SendPushNotification extends Notification
{
    use Queueable;

    protected $title;
    protected $message;
    protected $fcmTokens;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($title,$message,$fcmTokens)
    {
        $this->title = $title;
        $this->message = $message;
        $this->fcmTokens = $fcmTokens;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['firebase'];
    }

    public function toFirebase($notifiable)
    {
        return (new FirebaseMessage)
            ->withTitle($this->title)
            ->withBody($this->message)
            ->withPriority('high')->asMessage($this->fcmTokens);
    }
}

Now, You can use it as a notification like this:

use Notification;
use AppNotificationsSendPushNotification;

Notification::send(null,new SendPushNotification($title,$message,$fcmTokens));

Or

use AppNotificationsSendPushNotification;

auth()->user()->notify(new SendPushNotification($title,$message,$fcmTokens));

Now Run Project using Following Command:

php artisan serve

Thank you for reading this blog.

It’d be a good idea to follow along with the simple demo app that can be found in this GitHub repo.

Also see: Build Crud App with Laravel and Vue.js

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

 

Hope this code and post will helped you for implement Firebase Push Notification Laravel Tutorial. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US