Created
March 18, 2024 04:45
-
-
Save erdum/cef17685fa50b6507e6821e55866e24b to your computer and use it in GitHub Desktop.
Realtime Notification Mechanism Using Firestore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Kreait\Firebase\Factory; | |
use Google\Cloud\Firestore\FieldValue; | |
use Throwable; | |
class FirestoreNotificationService | |
{ | |
protected $db; | |
public function __construct() | |
{ | |
$firebase = (new Factory)->withServiceAccount( | |
base_path() | |
. DIRECTORY_SEPARATOR | |
. config('firebase.projects.app.credentials') | |
); | |
$this->db = $firebase->createFirestore()->database(); | |
} | |
public function push_notification( | |
string $message, | |
string|null $recipient_id = null, | |
string $type = 'message' | |
) | |
{ | |
$data = [ | |
'type' => $type, | |
'message' => $message, | |
'timestamp' => FieldValue::serverTimestamp(), | |
'read' => false, | |
'recipient_id' => $recipient_id | |
]; | |
try { | |
$ref = $this->db->collection('notifications') | |
->add($data); | |
return $ref->id(); | |
} catch (\Throwable $e) { | |
dd($e); | |
} | |
} | |
public function remove_notifications(array $notification_ids) | |
{ | |
$batch = $this->db->batch(); | |
foreach ($notification_ids as $id) { | |
$ref = $this->db->collection('notifications')->document($id); | |
$batch->delete($ref); | |
} | |
$batch->commit(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment