Published in


Firebase Push Notification Laravel 9 Tutorial

July 23, 2022, Originally published at ・6 min read

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 9 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 9.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.

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 Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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 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 = [
* 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:

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 App\Http\Controllers\HomeController;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');

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",
// 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="Kutia\Larafirebase\Providers\LarafirebaseServiceProvider"

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.

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 */ Larafirebase::withTitle($request->title)
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 App\Notifications;use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Kutia\Larafirebase\Messages\FirebaseMessage;
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 App\Notifications\SendPushNotification;
Notification::send(null,new SendPushNotification($title,$message,$fcmTokens));


use App\Notifications\SendPushNotification;auth()->user()->notify(new SendPushNotification($title,$message,$fcmTokens));

Now Run Project using Following Command:

php artisan serve

Thank you for reading this blog.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Smit Pipaliya

Smit Pipaliya

I am Senior Developer at ServerAvatar Technology.