1. Go to this page and download the library: Download lepresk/laravel-onesignal library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lepresk / laravel-onesignal example snippets
use Lepresk\LaravelOnesignal\Facades\OneSignal;
use Lepresk\LaravelOnesignal\PushMessage;
$message = (new PushMessage())
->withTitle('Hello World')
->withBody('This is a test notification')
->toExternalUserIds([1, 2, 3]);
$response = OneSignal::send($message);
if ($response->isSuccessful()) {
echo "Notification sent! ID: " . $response->getNotificationId();
}
namespace App\Notifications;
use Illuminate\Notifications\Notification;
use Lepresk\LaravelOnesignal\PushMessage;
class WelcomeNotification extends Notification
{
public function via($notifiable): array
{
return ['push'];
}
public function toPush($notifiable): PushMessage
{
return (new PushMessage())
->withTitle('Welcome!')
->withBody('Thanks for joining our platform')
->toUser($notifiable->onesignal_id);
}
}
// Target by tag
$message->toTag('user_type', 'premium');
$message->toTag('subscription_level', 'gold', '=');
$message = (new PushMessage())
->withTitle('New Message')
->withBody('You have a new message')
->addData('message_id', 456)
->addData('conversation_id', 789);
$message = (new PushMessage())
->withTitle('Check this out!')
->withBody('New image available')
->withImage('https://example.com/image.jpg')
->addButton('view', 'View Details', 'https://example.com/details')
->addButton('dismiss', 'Dismiss');
$message = (new PushMessage())
->withTitle('Title')
->withBody('Body')
->setTTL(3600)
->withIntelligentDeliveryDelayed()
->withName('campaign-2024-01');
use Lepresk\LaravelOnesignal\Events\NotificationSending;
use Lepresk\LaravelOnesignal\Events\NotificationSent;
use Lepresk\LaravelOnesignal\Events\NotificationFailed;
// In your EventServiceProvider
protected $listen = [
NotificationSending::class => [
// Handle before sending
],
NotificationSent::class => [
// Handle after successful send
],
NotificationFailed::class => [
// Handle when send fails
],
];
namespace App\Listeners;
use Lepresk\LaravelOnesignal\Events\NotificationSent;
use Illuminate\Support\Facades\Log;
class LogNotificationSent
{
public function handle(NotificationSent $event): void
{
Log::info('OneSignal notification sent', [
'notification_id' => $event->response->getNotificationId(),
'recipients' => $event->response->getRecipients(),
]);
}
}