- Регистрация
- 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:
If you don't already have a Firebase project, follow these steps:
Open your terminal and navigate to your Laravel project directory. Install the package using Composer:
composer require devkandil/notifire
Step 3: Configure Firebase Credentials
FIREBASE_PROJECT_ID=your-project-id
# Move the downloaded JSON file to your project
mv /path/to/your-firebase-credentials.json storage/firebase.json
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:
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
// In App\Models\User.php
protected $fillable = [
// existing fields...
'fcm_token',
];
// 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:
For Laravel 11:
Sanctum comes pre-installed in Laravel 11. Simply run the Sanctum installation command:
php artisan install:api
This command will:
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,
],
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:
Logging
The package automatically logs all notification attempts. You can find the logs in your Laravel log files with the following contexts:
Common Issues
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!
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:
- A Laravel project (version 8.0 or higher recommended)
- Composer installed
- A Firebase project with FCM enabled
- A service account JSON file from Firebase
If you don't already have a Firebase project, follow these steps:
- Go to the
- Click "Add project" and follow the setup wizard
- Once your project is created, navigate to Project Settings
- Click on the "Service accounts" tab
- Click "Generate new private key" to download your Firebase service account credentials JSON file
- Make note of your Firebase project ID, which you'll need later
Open your terminal and navigate to your Laravel project directory. Install the package using Composer:
composer require devkandil/notifire
Step 3: Configure Firebase Credentials
- Add your Firebase project ID to your .env file:
FIREBASE_PROJECT_ID=your-project-id
- 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
Step 3: Publish Package FilesImportant: Make sure to add storage/firebase.json to your .gitignore file to keep your credentials secure.
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)
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
- Update your User model to make the fcm_token field fillable:
// In App\Models\User.php
protected $fillable = [
// existing fields...
'fcm_token',
];
- 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:
- 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,
],
- 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:
| Option | Description |
|---|---|
| Title | The notification title |
| Body | The notification body text |
| Image | An image URL to display in the notification |
| Icon | An icon to display with the notification |
| Color | The color for the notification (in hexadecimal format) |
| Sound | The sound to play when the notification is received |
| Click Action | The action to perform when notification is clicked |
| Priority | The notification priority level |
| Additional Data | Additional data to send with the notification |
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
Common Issues
Firebase credentials not found
- Make sure the Firebase service account JSON file is located at the path specified in your configuration.
Invalid FCM token
- Ensure the FCM token is valid and properly formatted.
- Check that the token is being correctly stored in your database.
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.
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.
Enable more verbose logging in your Laravel application by setting the log level to debug in config/logging.php.
Use the Firebase Console to send test messages directly to your device's FCM token.
Check the browser console (for web applications) or logcat (for Android applications) for any Firebase-related errors.
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!