Firebase Push Notification Laravel 10 Tutorial

Firebase Push Notification Laravel 10 Tutorial

In this post we will give you information about Firebase Push Notification Laravel 10 Tutorial. Hear we will give you detail about Firebase Push Notification Laravel 10 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, grow their user base, and earn profit. It is built on Google’s infrastructure. Firebase is categorized as a NoSQL database program, that 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 a 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.

Firebase Push Notification Laravel 10 Tutorial Example

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:^9.0 lara9fire-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 the .env file, and set database detail as follow:


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

Laravel has just released “laravel 10.19” with a major change. There is no more webpack.mix.js file in the laravel root in the place of the webpack.mix.js file vite.config.js file is introduced. You must follow this article for the assets building.

See also  How to get latitude longitude from mysql in Laravel?

Read More: How to Install Bootstrap 5 in Laravel 10 With Vite

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"


use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class AddFcmTokenColumnToUsersTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::table('users', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()
        Schema::table('users', function (Blueprint $table) {

after updating the migration file run the following command:

php artisan migrate


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 = [

     * The attributes that should be hidden for arrays.
     * @var array
    protected $hidden = [

     * The attributes that should be cast to native types.
     * @var array
    protected $casts = [
        'email_verified_at' => 'datetime',

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:

See also  CSS Animated Backgrounds code and Demo

1. Create Firebase Project

2. Create a Web App in created Project

3. Web App Configuration Detail

Step 6: Add Route and Update Controller


public function updateToken(Request $request){
        return response()->json([
    }catch(Exception $e){
        return response()->json([

add a route in routes/web.php

use AppHttpControllersHomeController;

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


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

Step 7: Add Firebase Code


<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src=""></script>
<script src=""></script>

<!-- TODO: Add SDKs for Firebase products that you want to use -->

    // Your web app's Firebase configuration
    var firebaseConfig = {
        authDomain: "",
        projectId: "XXXXXXXXXX",
        storageBucket: "",
        messagingSenderId: "XXXXXXXXXX",
        appId: "1:XXXXXXXXX:web:XXXXXXXXXXXXX"
    // Initialize Firebase

    const messaging = firebase.messaging();

    function initFirebaseMessagingRegistration() {
        messaging.requestPermission().then(function () {
            return messaging.getToken()
        }).then(function(token) {
  "{{ route('fcmToken') }}",{

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

        new Notification(title, {body});

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

    projectId: "XXXXXXXX",
    messagingSenderId: "XXXXXXXXX",
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:


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.

See also  How to change a port number in Next.js app

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:


public function notification(Request $request){

        $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 */


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

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

Example usage in Notification class:

First Create a Notification using the following command:

php artisan make:notification SendPushNotification


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)

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

use Notification;
use AppNotificationsSendPushNotification;

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


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.

Also see: How to Install Multiple PHP Versions on Ubuntu 22.04

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 10 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