Hello, web developers! This article will explore how to send web push notifications in Laravel 11 using Firebase. Push notifications allow you to notify users when new emails or messages are available for them to sync.
Firebase Push Notification is a free and easy-to-use service you can implement using your Google account. Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages to Android, iOS, and web applications at no cost.
In this tutorial, I’ll show you how to implement "Firebase Web Push Notifications" in a Laravel 11 application. Firebase offers a real-time database and backend as a service, allowing developers to synchronize data across clients and store it in Firebase's cloud effortlessly.
Laravel 11 Firebase Push Notification
In this step, we will log in to Firebase Console and create a new project for Laravel Firebase push notification.
Now, install the laravel 11 application using the following command
composer create-project --prefer-dist laravel/laravel laravel_11_firebase_example
Now, create a login system using the auth command in laravel 11 using the following command.
composer require laravel/ui
php artisan ui bootstrap --auth // For Generate Auth
npm install // TO Install NPM
npm run dev
In this step, we'll add a new row "device_token" in the user's table as well as the model.
php artisan make:migration add_column_device_token
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddColumnDeviceTokenToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('device_token')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
}
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;
protected $fillable = [
'name',
'email',
'password',
'device_token'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now, run the following command to run the migration.
php artisan migrate
Now, we'll define the routes into the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::post('/save-push-notification-token', [HomeController::class, 'savePushNotificationToken'])->name('save-push-notification-token');
Route::post('/send-push-notification', [HomeController::class, 'sendPushNotification'])->name('send.push-notification');
Then, we'll create HomeController and add savePushNotificationToken() and sendPushNotification() functions.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('home');
}
public function savePushNotificationToken(Request $request)
{
auth()->user()->update(['device_token'=>$request->token]);
return response()->json(['token saved successfully.']);
}
public function sendPushNotification(Request $request)
{
$firebaseToken = User::whereNotNull('device_token')->pluck('device_token')->all();
$SERVER_API_KEY = 'Enter_Your_Server_Key';
$data = [
"registration_ids" => $firebaseToken,
"notification" => [
"title" => $request->title,
"body" => $request->body,
]
];
$dataString = json_encode($data);
$headers = [
'Authorization: key=' . $SERVER_API_KEY,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
dd($response);
}
}
Now, we'll update the home.blade.php file.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<center><h2>Laravel 11 Firebase Push Notification - Websolutionstuff</h2></center>
<div class="col-md-8">
<center>
<button id="btn-nft-enable" onclick="initFirebaseMessagingRegistration()" class="btn btn-danger btn-xs btn-flat">Allow for Notification</button>
</center><br>
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
<form action="{{ route('send.push-notification') }}" method="POST">
@csrf
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label>Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<button type="submit" class="btn btn-primary">Send Notification</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-messaging.js"></script>
<script>
var firebaseConfig = {
apiKey: "XXXX",
authDomain: "XXXX.firebaseapp.com",
projectId: "XXXX",
storageBucket: "XXXX.appspot.com",
messagingSenderId: "XXXX",
databaseURL: "https://Your_Project_ID.firebaseio.com",
appId: "XXXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
function initFirebaseMessagingRegistration() {
messaging
.requestPermission()
.then(function () {
return messaging.getToken({ vapidKey: 'Your_Public_Key' })
})
.then(function(token) {
console.log(token);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route("save-push-notification-token") }}',
type: 'POST',
data: {
token: token
},
dataType: 'JSON',
success: function (response) {
alert('Token saved successfully.');
},
error: function (err) {
console.log('User Chat Token Error'+ err);
},
});
}).catch(function (err) {
console.log('User Chat Token Error'+ err);
});
}
messaging.onMessage(function(payload) {
const noteTitle = payload.notification.title;
const noteOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
new Notification(noteTitle, noteOptions);
});
</script>
@endsection
Next, we'll create firebase-messaging-sw.js in the public folder. So, add the below code in the js file.
importScripts('https://www.gstatic.com/firebasejs/8.3.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.0/firebase-messaging.js');
firebase.initializeApp({
apiKey: "XXXX",
authDomain: "XXXX.firebaseapp.com",
databaseURL: "https://Your_Project_Id.firebaseio.com",
projectId: "XXXX",
storageBucket: "XXXX.appspot.com",
messagingSenderId: "XXXX",
appId: "XXXX"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
const notificationTitle = "Background Message Title";
const notificationOptions = {
body: "Background Message body.",
icon: "/itwonders-web-logo.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions,
);
});
Output:
You might also like:
In this article, we will see how file uploads in react js. File uploading means a user from a client machine wants...
Sep-05-2022
In this article, we will see laravel 9 barcode generator example. In this example we will use the milon/barcod...
Mar-26-2022
Hello, web developers! In this article, we'll see how to create a dynamic dropdown using Vue.js with laravel 11. Als...
Jul-22-2024
In this tutorial, we will see laravel 9 generate pdf file using dompdf. For generating pdf files we will use the la...
Feb-25-2022