Geek Culture
Published in

Geek Culture

Laravel Tutorial : Push Notification With Firebase Laravel 9

Hello, how are you all friends, this time we will discuss how to create notifications using Laravel. Push Notification with Laravel firebase is very important for client-based applications, because it will be useful for notifications when there are new messages.

Push notifications are clickable pop-up messages that appear in your users’ browsers regardless of the device they are using or the browser they are using. They serve as a quick communication channel that allows companies to pass messages, offers or other information to their customers.

Friends can study other tutorials:

Laravel Tutorial : Creating Dynamic Dependent With Select2

Laravel Tutorial ~ Laravel Eloquent Relationships

Using Scope in Laravel

Firebase

Firebase is a service from Google to provide convenience and even make it easier for application developers to develop their applications. Firebase aka BaaS (Backend as a Service) is a solution offered by Google to speed up developer work.

By using Firebase, app developers can focus on developing applications without putting a lot of effort into the backend.

FCM (Firebase Cloud Messaging)

FCM (Firebase Cloud Messaging) which provides a reliable connection and of course saves battery between servers and between devices. So you can send and receive messages and notifications on Android, iOS, and the web at no cost.

To target advanced messages, you can easily target messages using pre-defined segments using demographics and behavior. You can target messages to devices that have subscribed to specific topics. In addition, you can also target only one device to get detailed data information. Usually this is done for the testing process.

These notification messages are fully integrated with Google Analytics for Firebase, so you have access to detailed engagement and conversion tracking. Well, you can monitor an effectiveness from a single dashboard without the need for coding or creating your own program.

  1. Install Laravel

We will do laravel installation. Open your terminals, and enter the command below.

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

2. Setting Database

After doing the installation now we will do the database connection.

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

3. Install Library Auth

Now, we will create login, register and dashboard. enter the command below in the terminal of all friends.

composer require laravel/uiphp artisan ui bootstrap --authnpm install && npm run dev

4. Migration

This time we will migrate all existing tables.

php artisan migrate

Next we will create a migration to add the fcm_token kolom column.

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

database/migrations/2022_06_28_063655_add_fcm_token_column_to_users_table.php

<?php

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) {
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('fcm_token');
});
});
}

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

After updating the migration, run the migration command again.

php artisan migrate

5. Model Settings

open and customize the app/Models/Users.php file.

<?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;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'fcm_token'
];

/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
'remember_token',
];

/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

6. Create a Firebase Project

a. Create Firebase Project

b. Create a Web App in created Project

c. Web App Configuration Detail

7. Controller

app\Http\Controllers\HomeController.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 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');
Route::post('/send-notification',[HomeController::class,'notification'])->name('notification');

8. Kode Firebase

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 a firebase-messaging-sw.js file in the 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});
});

10. Push Notification

To get notifications, we use the Larafirebase package.

Install Larafirebase

composer require kutia-software-company/larafirebasephp artisan vendor:publish --provider="Kutia\Larafirebase\Providers\LarafirebaseServiceProvider"

Add the Firebase Server Key in the .env file.

FIREBASE_SERVER_KEY=XXXXXXXXXXXXXXXXXXXXX

config/larafirebase.php

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

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.');
}
}

We create Notifications using the command:

php artisan make:notification SendPushNotification

app\Notifications\SendPushNotification.php

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)
->withTitle($this->title)
->withBody($this->message)
->withPriority('high')->asMessage($this->fcmTokens);
}
}

Can use the function, for example:

use Notification;
use App\Notifications\SendPushNotification;

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

Now run the command:

php artisan serve

Thus the tutorial this time I give, hopefully useful.

Thanks.

--

--

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