Integrating OneSignal Push Notifications in Laravel
Push notifications are essential for modern web applications. They keep users engaged and informed about important updates. In this guide, I'll show you how to integrate OneSignal with Laravel.
Why OneSignal?
OneSignal is a powerful, free push notification service that supports:
- Web Push (Chrome, Firefox, Safari)
- Mobile Push (iOS, Android)
- In-App Messages
- Email notifications
It's reliable, scalable, and has a generous free tier perfect for most applications.
Installation
First, install the OneSignal PHP SDK:
composer require onesignal/onesignal-php-api
Configuration
Add your OneSignal credentials to .env:
ONESIGNAL_APP_ID=your_app_id
ONESIGNAL_REST_API_KEY=your_rest_api_key
Create a configuration file config/onesignal.php:
<?php
return [
'app_id' => env('ONESIGNAL_APP_ID'),
'rest_api_key' => env('ONESIGNAL_REST_API_KEY'),
];
Creating a Notification Service
Create a service to handle OneSignal operations:
<?php
namespace App\Services;
use OneSignal\OneSignal;
class PushNotificationService
{
protected OneSignal $client;
public function __construct()
{
$this->client = new OneSignal(
config('onesignal.app_id'),
config('onesignal.rest_api_key')
);
}
public function sendToUser(string $userId, string $message, array $data = []): void
{
$this->client->notifications->create([
'contents' => ['en' => $message],
'include_external_user_ids' => [$userId],
'data' => $data,
]);
}
public function sendToAll(string $message, array $data = []): void
{
$this->client->notifications->create([
'contents' => ['en' => $message],
'included_segments' => ['All'],
'data' => $data,
]);
}
}
Usage in Controllers
use App\Services\PushNotificationService;
class OrderController extends Controller
{
public function __construct(
protected PushNotificationService $pushNotification
) {}
public function store(Request $request)
{
$order = Order::create($request->validated());
$this->pushNotification->sendToUser(
$order->user_id,
"Your order #{$order->id} has been confirmed!",
['order_id' => $order->id]
);
return response()->json($order);
}
}
Laravel Notifications
For a more Laravel-native approach, create a notification channel:
<?php
namespace App\Notifications\Channels;
use App\Services\PushNotificationService;
use Illuminate\Notifications\Notification;
class OneSignalChannel
{
public function __construct(
protected PushNotificationService $pushNotification
) {}
public function send($notifiable, Notification $notification): void
{
$message = $notification->toOneSignal($notifiable);
$this->pushNotification->sendToUser(
$notifiable->onesignal_id,
$message['body'],
$message['data'] ?? []
);
}
}
Then use it in your notifications:
<?php
namespace App\Notifications;
use App\Notifications\Channels\OneSignalChannel;
use Illuminate\Notifications\Notification;
class OrderShipped extends Notification
{
public function via($notifiable): array
{
return [OneSignalChannel::class, 'mail'];
}
public function toOneSignal($notifiable): array
{
return [
'body' => 'Your order has been shipped!',
'data' => [
'order_id' => $this->order->id,
'tracking_number' => $this->order->tracking_number,
],
];
}
}
Best Practices
- Queue notifications: Always queue push notifications to avoid blocking requests
- Handle failures gracefully: Wrap OneSignal calls in try-catch blocks
- Personalize messages: Use user data to make notifications relevant
- Test thoroughly: Use OneSignal's test mode before going live
- Monitor delivery: Check OneSignal dashboard for delivery rates
Conclusion
OneSignal makes it easy to add push notifications to Laravel apps. With proper implementation and best practices, you can significantly improve user engagement.
The code examples above provide a solid foundation. Customize them based on your specific needs and enjoy better user engagement!