• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Notifier: A Comprehensive Installation and Configuration Guide to integrate Firebase Cloud Messaging (FCM)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In today's mobile-first world, push notifications have become essential for engaging users with timely updates and information. For Laravel developers looking to integrate Firebase Cloud Messaging (FCM) into their applications, the Laravel FCM Notifier package by

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

offers an elegant solution that aligns perfectly with Laravel's design philosophy.

This comprehensive guide will walk you through setting up and configuring the Notifier package, providing practical examples for all available notification methods.

What is

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

?



Notifier is a package that seamlessly integrates Firebase Cloud Messaging with Laravel's notification system. It provides a fluent interface for building notifications, supports both simple and complex FCM messages, automatically logs delivery status, and includes database migrations for storing FCM tokens.

Prerequisites


Before installing Notifier, ensure you have:

  1. A Laravel project (version 8.0 or higher recommended)
  2. Composer installed
  3. A Firebase project with FCM enabled
  4. A service account JSON file from Firebase
Step 1: Create a Firebase Project


If you don't already have a Firebase project, follow these steps:

  1. Go to the

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  2. Click "Add project" and follow the setup wizard
  3. Once your project is created, navigate to Project Settings
  4. Click on the "Service accounts" tab
  5. Click "Generate new private key" to download your Firebase service account credentials JSON file
  6. Make note of your Firebase project ID, which you'll need later
Step 2: Install the Package


Open your terminal and navigate to your Laravel project directory. Install the package using Composer:


composer require devkandil/notifire
Step 3: Configure Firebase Credentials

  1. Add your Firebase project ID to your .env file:

FIREBASE_PROJECT_ID=your-project-id
  1. Place your Firebase service account credentials JSON file in your Laravel storage directory:

# Move the downloaded JSON file to your project
mv /path/to/your-firebase-credentials.json storage/firebase.json
Important: Make sure to add storage/firebase.json to your .gitignore file to keep your credentials secure.
Step 3: Publish Package Files


Publish the package configuration and migration files:


# Publish everything
php artisan vendor:publish --provider="DevKandil\NotiFire\FcmServiceProvider"

# Alternatively, publish specific components
php artisan vendor:publish --tag=fcm-config # Configuration file
php artisan vendor:publish --tag=fcm-migrations # Database migrations
php artisan vendor:publish --tag=fcm-notifications # Example notification
php artisan vendor:publish --tag=fcm-contracts # Interface contracts
php artisan vendor:publish --tag=fcm-enums # Enums (MessagePriority)
php artisan vendor:publish --tag=fcm-traits # Traits (HasFcm)
Step 4: Customize Configuration (Optional)


If you need to customize the package's behavior, you can modify the published configuration file at config/fcm.php. The most common configuration options include:

  • credentials_path: The path to your Firebase service account JSON file
  • project_id: Your Firebase project ID (defaults to using the value from your .env file)
Step 5: Run Migrations


Run the migrations to create the necessary database tables:


php artisan migrate

This will add the fcm_token field to your users table.

Step 6: Update Your User Model

  1. Update your User model to make the fcm_token field fillable:

// In App\Models\User.php
protected $fillable = [
// existing fields...
'fcm_token',
];
  1. Add the HasFcm trait to your User model:

// In App\Models\User.php
use DevKandil\NotiFire\Traits\HasFcm;

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

// Your existing code...
}
Step 7: Set Up Token Updates (Optional)


The package includes a built-in controller for updating FCM tokens. If you want to enable this functionality, ensure your API routes are properly set up with Sanctum authentication:

  1. Configure Sanctum for your application:

For Laravel 11:
Sanctum comes pre-installed in Laravel 11. Simply run the Sanctum installation command:


php artisan install:api

This command will:

  • Configure Sanctum
  • Set up the necessary API routes
  • Create the required database migrations
  • Set up the proper middleware configuration

For Laravel 10 or earlier:
Install and configure Sanctum manually:


composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Then add the Sanctum middleware to your api middleware group in app/Http/Kernel.php:


'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
  1. Add the Sanctum trait to your User model (if you haven't already):

use Laravel\Sanctum\HasApiTokens;

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

// Your existing code...
}

Now, your frontend application can update the FCM token by making a POST request to /fcm/token with the following payload:


{
"fcm_token": "user-fcm-token-here"
}
Step 8: Create a Custom Notification (Optional)


If you want to create a custom notification, you can use the Laravel artisan command to generate a new notification class:


php artisan make:notification PushNotification

Then, modify the generated notification class to include FCM channel support:


<?php

namespace App\Notifications;

use DevKandil\NotiFire\FcmMessage;
use DevKandil\NotiFire\Enums\MessagePriority;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

class PushNotification extends Notification
{
use Queueable;

protected $title;
protected $body;

/**
* Create a new notification instance.
*/
public function __construct($title, $body)
{
$this->title = $title;
$this->body = $body;
}

/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['fcm'];
}

/**
* Get the FCM representation of the notification.
*/
public function toFcm(object $notifiable): FcmMessage
{
return FcmMessage::create($this->title, $this->body)
->image('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
->sound('default')
->clickAction('OPEN_ACTIVITY')
->icon('notification_icon')
->color('#FF5733')
->priority(MessagePriority::HIGH)
->data([
'notification_id' => uniqid('notification_'),
'timestamp' => now()->toIso8601String(),
]);
}
}
Using Laravel FCM Notifier


Now that everything is set up, let's explore the different ways to send notifications using Laravel FCM Notifier.

Method 1: Using the Facade


The Facade provides a fluent interface for sending notifications:


use DevKandil\NotiFire\Facades\Fcm;
use DevKandil\NotiFire\Enums\MessagePriority;

// Get the authenticated user
$user = auth()->user();

// Send notification
Fcm::withTitle('New Message')
->withBody('You have a new message from Sarah.')
->withImage('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
->withSound('default')
->withPriority(MessagePriority::HIGH)
->withIcon('message_icon')
->withColor('#000000')
->sendNotification($user->fcm_token);
Method 2: Using Dependency Injection


You can also use dependency injection to get an instance of the FCM service:


use DevKandil\NotiFire\Contracts\FcmServiceInterface;
use DevKandil\NotiFire\Enums\MessagePriority;

// Get the authenticated user
$user = auth()->user();

// Get the FCM service instance
$fcm = app(FcmServiceInterface::class);

// Send notification
$fcm->withTitle('Order Shipped')
->withBody('Your order #1234 has been shipped and is on its way.')
->withImage('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
->withIcon('shipping_truck')
->withColor('#FF5733')
->withSound('default')
->withPriority(MessagePriority::HIGH)
->withAdditionalData(['key' => 'value'])
->sendNotification($user->fcm_token);
Method 3: Using Laravel's Notification System


If you prefer to use Laravel's built-in notification system:


use App\Notifications\PushNotification;
// Or use the example notification provided by the package
use DevKandil\NotiFire\Notifications\ExampleNotification;

// Get the authenticated user
$user = auth()->user();

// Send notification
$user->notify(new ExampleNotification('? Hot Deal Just for You!', 'Get 20% off your next purchase. Offer ends tonight!'));

The ExampleNotification class includes the following implementation for the FCM channel:


/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['fcm'];
}

/**
* Get the FCM representation of the notification.
*/
public function toFcm(object $notifiable): FcmMessage
{
return FcmMessage::create($this->title, $this->body)
->image('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

')
->sound('default')
->clickAction('OPEN_ACTIVITY')
->icon('notification_icon')
->color('#FF5733')
->priority(MessagePriority::HIGH)
->data([
'notification_id' => uniqid('notification_'),
'timestamp' => now()->toIso8601String(),
]);
}
Method 4: Using the HasFcm Trait


The HasFcm trait provides a convenient way to send notifications directly from your User model:


use DevKandil\NotiFire\Enums\MessagePriority;

// Get the authenticated user
$user = auth()->user();

// Send notification
$user->sendFcmNotification(
'Appointment Reminder',
'Don’t forget your appointment with Dr. Smith at 3:00 PM today.',
[
'image' => '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

',
'sound' => 'default',
'click_action' => 'OPEN_ACTIVITY',
'icon' => 'calendar_icon',
'color' => '#FF5733',
'data' => ['key' => 'value'],
'priority' => MessagePriority::HIGH
]
);
Method 5: Using Raw FCM Messages


For complete control over the FCM message payload, you can use the fromRaw method:


use DevKandil\NotiFire\Contracts\FcmServiceInterface;
use DevKandil\NotiFire\Facades\Fcm;

// Get the authenticated user
$user = auth()->user();

// Method 1: Using dependency injection
$fcm = app(FcmServiceInterface::class);

// Method 2: Using the Facade
$fcm = Fcm::build();

// The fromRaw method accepts a complete FCM message payload and returns a boolean
// indicating whether the message was sent successfully
$success = $fcm->fromRaw([
'message' => [
'token' => $user->fcm_token,
'notification' => [
'title' => 'Login Attempt Detected',
'body' => 'A new login to your account was detected from a new device.',
],
'android' => [
'priority' => 'high',
],
'data' => [
'key' => 'value',
],
],
])->send();
Advanced Configuration

Customizing the Firebase Credentials Path


If you need to store your Firebase credentials in a different location, you can update the credentials_path in config/fcm.php:


'credentials_path' => env('FIREBASE_CREDENTIALS_PATH', storage_path('your-custom-path/firebase-credentials.json')),
Customizing FCM Options


Each notification method allows you to customize various aspects of the FCM message:

OptionDescription
TitleThe notification title
BodyThe notification body text
ImageAn image URL to display in the notification
IconAn icon to display with the notification
ColorThe color for the notification (in hexadecimal format)
SoundThe sound to play when the notification is received
Click ActionThe action to perform when notification is clicked
PriorityThe notification priority level
Additional DataAdditional data to send with the notification
Logging


The package automatically logs all notification attempts. You can find the logs in your Laravel log files with the following contexts:

  • Successful notifications: info level with message ID
  • Failed notifications: error level with error details
  • Missing FCM tokens: warning level
Troubleshooting

Common Issues


  1. Firebase credentials not found
    • Make sure the Firebase service account JSON file is located at the path specified in your configuration.

  2. Invalid FCM token
    • Ensure the FCM token is valid and properly formatted.
    • Check that the token is being correctly stored in your database.

  3. Notification not received
    • Verify that the device has an internet connection.
    • Check that the notification permission has been granted on the device.
    • Look at the Laravel logs for any error messages.

  4. Token not updating
    • Make sure your frontend is correctly sending the token to your backend.
    • Verify that the update endpoint is properly configured and accessible.
Debugging Tips


  1. Enable more verbose logging in your Laravel application by setting the log level to debug in config/logging.php.


  2. Use the Firebase Console to send test messages directly to your device's FCM token.


  3. Check the browser console (for web applications) or logcat (for Android applications) for any Firebase-related errors.
Conclusion


Notifier provides a robust and developer-friendly solution for integrating Firebase Cloud Messaging into your Laravel applications. With its fluent interface and multiple notification methods, you can easily add push notifications to enhance user engagement in your applications.

By following this comprehensive guide, you should now have a fully configured Laravel FCM Notifier setup that's ready to send push notifications to your users' devices. Happy coding!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу