In this tutorial you will learn about the Laravel 8 Firebase Web Push Notification Example and its application with practical example.
In this Laravel Firebase Web Push Notification Example tutorial, I’ll show you how to integrate and send web push notification using Firebase in laravel 8 application. In this tutorial you will learn integrate Firebase and send web push notification using Firebase in laravel project. In this article I will share example to integrate Firebase web push notification in laravel.
Laravel 8 Firebase Web Push Notification Example
In this step by step tutorial I will demonstrate you the process to integrate Firebase and to send web push notification in laravel. Please follow the instruction given below:
Step 1: Create Firebase Project and App
First of all you need to visit Firebase Console and create a project. then you have to create web app on that project. Then copy firebase configuration details.
Step 2: Install Laravel
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blogFirebase |
Step 3: Create Auth using scaffold
Now, we will create auth scaffold using following command:
Laravel UI Package
1 |
composer require laravel/ui |
Generate auth
1 2 3 |
php artisan ui bootstrap --auth npm install npm run dev |
Step 4: Create Migration and Update Model
In this step we will create migration file to add “device_token” in users table. Please run the following command:
1 |
php artisan make:migration add_column_device_token |
database/migrations/2020_10_23_144523_add_column_device_token.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddColumnDeviceToken extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('device_token')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { } } |
app/Models/User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?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; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'device_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', ]; } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Step 5: Create Route
Now we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::post('/save-token', [App\Http\Controllers\HomeController::class, 'saveToken'])->name('save-token'); Route::post('/send-notification', [App\Http\Controllers\HomeController::class, 'sendNotification'])->name('send.notification'); |
Step 6: Add Method on Controller
Now add following methods in HomeController:
app/Http/Controllers/HomeController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { return view('home'); } /** * Write code on Method * * @return response() */ public function saveToken(Request $request) { auth()->user()->update(['device_token'=>$request->token]); return response()->json(['token saved successfully.']); } /** * Write code on Method * * @return response() */ public function sendNotification(Request $request) { $firebaseToken = User::whereNotNull('device_token')->pluck('device_token')->all(); $SERVER_API_KEY = 'XXXXXX'; $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_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); $response = curl_exec($ch); dd($response); } } |
Step 7: Update Blade File
Now we have to update home.blade.php file to send notification and allow notification button.
resources/views/home.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-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> <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.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://www.gstatic.com/firebasejs/7.23.0/firebase.js"></script> <script> var firebaseConfig = { apiKey: "XXXX", authDomain: "XXXX.firebaseapp.com", databaseURL: "https://XXXX.firebaseio.com", projectId: "XXXX", storageBucket: "XXXX", messagingSenderId: "XXXX", appId: "XXXX", measurementId: "XXX" }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); function initFirebaseMessagingRegistration() { messaging .requestPermission() .then(function () { return messaging.getToken() }) .then(function(token) { console.log(token); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: '{{ route("save-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 |
Step 8: Create firebase-messaging-sw.js File
We have to also create firebase-messaging-sw.js in public folder and put bellow code.
public/firebase-messaging-sw.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* Give the service worker access to Firebase Messaging. Note that you can only use Firebase Messaging here, other Firebase libraries are not available in the service worker. */ importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js'); /* Initialize the Firebase app in the service worker by passing in the messagingSenderId. * New configuration for app@pulseservice.com */ firebase.initializeApp({ apiKey: "XXXX", authDomain: "XXXX.firebaseapp.com", databaseURL: "https://XXXX.firebaseio.com", projectId: "XXXX", storageBucket: "XXXX", messagingSenderId: "XXXX", appId: "XXXX", measurementId: "XXX" }); /* Retrieve an instance of Firebase Messaging so that it can handle background messages. */ const messaging = firebase.messaging(); messaging.setBackgroundMessageHandler(function(payload) { console.log( "[firebase-messaging-sw.js] Received background message ", payload, ); /* Customize notification here */ const notificationTitle = "Background Message Title"; const notificationOptions = { body: "Background Message body.", icon: "/itwonders-web-logo.png", }; return self.registration.showNotification( notificationTitle, notificationOptions, ); }); |
Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |