Okay, let's design and outline the implementation of a complex notification service in Laravel. This will leverage Laravel's built-in notification system and best practices like events/listeners and queues.
Core Concepts:
Laravel Notifications: The heart of the system. Allows defining notification classes that can be sent via multiple channels.
Notifiable Models: Your User model (or potentially separate Tenant, Staff, Customer models if you choose that structure) will use the Illuminate\Notifications\Notifiable trait.
Notification Classes: Specific classes for each type of notification (e.g., AppointmentAssigned, InvoiceCreated). These classes define how the notification data is formatted for each channel.
Channels: Drivers for delivering notifications (Database, Mail, custom channels like Expo, SMS).
Events & Listeners: Decouple notification sending from your core application logic. E.g., an AppointmentUpdated event triggers a SendAppointmentUpdateNotification listener.
Queues: Essential for performance. Sending emails or push notifications should happen in the background.
User Preferences: Allow users to choose which notifications they receive and via which channels.
Structure Events: Pass relevant data (models or IDs) in the event constructor.
php
// app/Events/AppointmentAssigned.php
namespace App\Events;
use App\Models\Appointment;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class AppointmentAssigned
{
use Dispatchable, SerializesModels;
public Appointment $appointment;
public User $assignedStaff;
public ?User $customer; // Customer might also need notification
public function __construct(Appointment $appointment, User $assignedStaff, ?User $customer)
{
$this->appointment = $appointment;
$this->assignedStaff = $assignedStaff;
$this->customer = $customer;
}
}
Define Listeners: Create listeners that will handle sending the notifications.
bash
php artisan make:listener SendAppointmentAssignedNotification --event=AppointmentAssigned
php artisan make:listener SendInvoiceCreatedNotification --event=InvoiceCreated
# ... and so on
Implement Listeners: Fetch recipients and dispatch the appropriate notification.
// routes/api.php
use App\Http\Controllers\Api\NotificationController;
use App\Http\Controllers\Api\UserDeviceController; // For managing tokens
Route::middleware('auth:sanctum')->group(function () {
Route::get('/notifications', [NotificationController::class, 'index']);
Route::post('/notifications/mark-as-read', [NotificationController::class, 'markAsRead']);
Route::post('/notifications/mark-all-read', [NotificationController::class, 'markAllRead']);
Route::get('/notifications/unread-count', [NotificationController::class, 'unreadCount']);
// Route to register/update Expo push token
Route::post('/user-devices', [UserDeviceController::class, 'store']);
Route::delete('/user-devices/{token}', [UserDeviceController::class, 'destroy']); // Allow removing specific token
});
Implement NotificationController:
php
8. Frontend Integration (Expo Example)
Get the push token: Use expo-notificationsgetExpoPushTokenAsync().
Register the token: Send the token to your /api/user-devices endpoint when the user logs in or the token changes.
Handle received notifications: Use addNotificationReceivedListener and addNotificationResponseReceivedListener from expo-notifications to handle taps and foreground notifications. Use the data payload to navigate within the app.
Fetch in-app notifications: Call your /api/notifications endpoint.
Mark as read: Call /api/notifications/mark-as-read when a user views notifications.
9. Future SMS Channel
Choose an SMS provider (Twilio, Vonage).
Install their PHP SDK (e.g., twilio/sdk).
Create a custom SmsChannel similar to the ExpoChannel, using the provider's SDK to send messages.
Create a toSms($notifiable) method in your notification classes.
Add a way for users to store and verify their phone numbers.
Add the SmsChannel::class to the via() method based on preferences.
This comprehensive structure provides a scalable and maintainable notification system in Laravel, covering multiple user types, notification types, and delivery channels while leveraging best practices. Remember to configure your .env file (Mail driver, Queue driver, potentially Expo credentials if needed server-side beyond the token), run migrations, and set up queue workers.
// app/Models/User.php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; // <--- Import Notifiable
use Laravel\Sanctum\HasApiTokens;
use App\Notifications\Channels\ExpoChannel; // <--- Import custom channel
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable; // <--- Use Notifiable
protected $fillable = [
'name',
'email',
'password',
'user_type',
'tenant_id',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
// Relationship to get Expo push tokens
public function devices()
{
return $this->hasMany(UserDevice::class);
}
/**
* Route notifications for the Expo channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string|array
*/
public function routeNotificationForExpo($notification)
{
// Return an array of tokens for the user
return $this->devices()->pluck('expo_push_token')->toArray();
}
/**
* Route notifications for the mail channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForMail($notification)
{
return $this->email;
}
// --- Helper methods for user type ---
public function isTenant(): bool
{
return $this->user_type === 'tenant';
}
public function isStaff(): bool
{
return $this->user_type === 'staff';
}
public function isCustomer(): bool
{
return $this->user_type === 'customer';
}
// --- (Optional) Relationship for Preferences ---
public function notificationPreferences()
{
return $this->hasMany(UserNotificationPreference::class);
}
// --- (Optional) Check Preference ---
public function wantsNotificationVia(string $notificationType, string $channel): bool
{
// Implement logic to check the 'user_notification_preferences' table
// or the JSON column on the users table. Default to true if no preference set.
$preference = $this->notificationPreferences()
->where('notification_type', $notificationType)
->where('channel', $channel)
->first();
return $preference ? $preference->is_enabled : true; // Default to enabled
}
}
// app/Models/UserDevice.php (Create this model)
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserDevice extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'expo_push_token',
'device_info',
'last_used_at',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
// (Optional) app/Models/UserNotificationPreference.php
// ... create model ...
// app/Listeners/SendAppointmentAssignedNotification.php
namespace App\Listeners;
use App\Events\AppointmentAssigned;
use App\Notifications\AppointmentAssigned as AppointmentAssignedNotification; // Your Notification class
use Illuminate\Contracts\Queue\ShouldQueue; // Implement ShouldQueue
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification;
class SendAppointmentAssignedNotification implements ShouldQueue // <--- Make it queueable
{
use InteractsWithQueue;
public function handle(AppointmentAssigned $event)
{
// Send notification to the assigned staff member
if ($event->assignedStaff) {
// Check preferences before notifying if you have that system
// if ($event->assignedStaff->wantsNotificationVia('appointment_assigned', '...')) {}
$event->assignedStaff->notify(new AppointmentAssignedNotification($event->appointment));
}
// Optionally notify the customer too
if ($event->customer) {
// Check preferences...
$event->customer->notify(new AppointmentAssignedNotification($event->appointment, true)); // Pass flag if message differs for customer
}
// Optionally notify the Tenant Owner
// $tenantOwner = $event->appointment->tenant->owner; // Assuming you have this relationship
// $tenantOwner->notify(...)
}
}
Register Events & Listeners: In app/Providers/EventServiceProvider.php.
// app/Notifications/AppointmentAssigned.php
namespace App\Notifications;
use App\Models\Appointment;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Notifications\Messages\ExpoMessage; // <-- Custom Expo Message class
use App\Notifications\Channels\ExpoChannel; // <-- Custom Expo Channel
class AppointmentAssigned extends Notification implements ShouldQueue // <-- Implement ShouldQueue
{
use Queueable;
public Appointment $appointment;
public bool $isForCustomer; // Flag to tailor message if needed
public function __construct(Appointment $appointment, bool $isForCustomer = false)
{
$this->appointment = $appointment;
$this->isForCustomer = $isForCustomer;
// Use $this->onQueue('notifications'); // Optional: dedicated queue
// Use $this->delay(now()->addMinutes(1)); // Optional: delay
}
/**
* Get the notification's delivery channels.
* Check user preferences here if implemented.
*
* @param mixed $notifiable (The User model instance)
* @return array
*/
public function via($notifiable): array
{
$channels = [];
// Example Preference Check (adapt if using JSON column)
// You might centralize this logic in the User model or a service
if ($notifiable->wantsNotificationVia('appointment_assigned', 'database')) {
$channels[] = 'database';
}
if ($notifiable->wantsNotificationVia('appointment_assigned', 'mail')) {
$channels[] = 'mail';
}
if ($notifiable->wantsNotificationVia('appointment_assigned', 'push') && $notifiable->devices()->exists()) {
// Only add push if they have a registered device token
$channels[] = ExpoChannel::class; // Use the custom channel class name
}
// if ($notifiable->wantsNotificationVia('appointment_assigned', 'sms')) {
// $channels[] = SmsChannel::class; // Future SMS channel
// }
// Fallback if no preferences are set or found
if (empty($channels)) {
// Sensible defaults - maybe database and email? Or just database?
$channels = ['database', 'mail'];
if($notifiable->devices()->exists()) {
$channels[] = ExpoChannel::class;
}
}
return $channels;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable): MailMessage
{
$subject = $this->isForCustomer
? "Your Appointment Details"
: "You have been assigned to an appointment";
$line1 = $this->isForCustomer
? "Details for your upcoming appointment:"
: "You have been assigned to appointment #{$this->appointment->id}";
return (new MailMessage)
->subject($subject)
->line($line1)
->line("Date: " . $this->appointment->start_time->format('Y-m-d H:i'))
// ->action('View Appointment', url('/appointments/'.$this->appointment->id)) // Add relevant action URL
->line('Thank you!');
}
/**
* Get the array representation of the notification (for database).
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable): array
{
// Data stored in the `data` column of the `notifications` table
return [
'appointment_id' => $this->appointment->id,
'title' => $this->isForCustomer ? "Appointment Update" : "New Appointment Assignment",
'message' => $this->isForCustomer
? "Your appointment on {$this->appointment->start_time->format('M d, Y')} has been confirmed/updated."
: "You've been assigned to appointment #{$this->appointment->id} on {$this->appointment->start_time->format('M d, Y')}.",
// Add any other relevant data needed for front-end display
'link' => '/appointments/'.$this->appointment->id, // Relative link for in-app navigation
];
}
/**
* Get the Expo Push representation of the notification.
*
* @param mixed $notifiable
* @return ExpoMessage
*/
public function toExpo($notifiable): ExpoMessage
{
$title = $this->isForCustomer ? "Appointment Update" : "New Assignment";
$body = $this->isForCustomer
? "Your appointment on {$this->appointment->start_time->format('M d, Y')} has been updated."
: "New appointment #{$this->appointment->id} on {$this->appointment->start_time->format('M d, Y')}.";
return (new ExpoMessage())
->title($title)
->body($body)
->data([ // Optional data payload for the app
'type' => 'appointment_assigned',
'appointment_id' => $this->appointment->id,
'_displayInForeground' => true, // Expo specific option
])
->sound('default') // Optional: default, null
->badge(1) // Optional: set badge count
->channelId('default'); // Optional: Android Channel ID
// ->priority('high'); // Optional: high, normal
}
}
Create Custom Expo Channel: Handles sending the push via Expo's API.
php
// app/Notifications/Channels/ExpoChannel.php
namespace App\Notifications\Channels;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http; // Use Laravel's HTTP Client
use Illuminate\Support\Facades\Log;
use Throwable;
class ExpoChannel
{
const EXPO_API_URL = 'https://exp.host/--/api/v2/push/send';
/**
* Send the given notification.
*
* @param mixed $notifiable (The User model)
* @param \Illuminate\Notifications\Notification $notification
* @return void
*/
public function send($notifiable, Notification $notification): void
{
// 1. Get the ExpoMessage payload from the notification
if (!method_exists($notification, 'toExpo')) {
Log::warning("Notification [" . get_class($notification) . "] is missing toExpo method.");
return;
}
$message = $notification->toExpo($notifiable);
if (!$message) {
return; // Nothing to send
}
// 2. Get the recipient's Expo push token(s)
$tokens = $notifiable->routeNotificationFor('Expo', $notification);
if (empty($tokens)) {
// Log::info("User {$notifiable->id} has no Expo push tokens.");
return; // No tokens to send to
}
// Ensure tokens is an array
$tokens = is_array($tokens) ? $tokens : [$tokens];
// 3. Format the request payload for Expo API
// Expo expects an array of message objects, even if sending only one type
$payloads = [];
foreach ($tokens as $token) {
if (!is_string($token) || strlen($token) < 5) {
Log::warning("Invalid Expo token format for user {$notifiable->id}: " . $token);
continue; // Skip invalid tokens
}
$payloads[] = array_merge($message->toArray(), ['to' => $token]);
}
if (empty($payloads)) {
Log::info("No valid payloads to send via Expo for notification [" . get_class($notification) . "] to user {$notifiable->id}.");
return;
}
// 4. Send the request to Expo
try {
$response = Http::acceptJson()
->post(self::EXPO_API_URL, $payloads); // Send array of payloads
if ($response->failed()) {
Log::error('Expo Push Failed: Status ' . $response->status(), [
'response_body' => $response->body(),
'user_id' => $notifiable->id,
'notification' => get_class($notification),
]);
// Optionally handle specific errors (e.g., DeviceNotRegistered)
$this->handleExpoErrors($response->json(), $notifiable);
} elseif ($response->successful()) {
// Optionally log success or handle receipts if needed
// Log::debug('Expo Push Sent Successfully:', ['response' => $response->json()]);
$this->handleExpoErrors($response->json(), $notifiable); // Still check for per-message errors
}
} catch (Throwable $e) {
Log::error('Expo Push Exception:', [
'message' => $e->getMessage(),
'user_id' => $notifiable->id,
'notification' => get_class($notification),
'trace' => $e->getTraceAsString() // careful with logging full traces in prod
]);
}
}
/**
* Handle potential errors returned by Expo API, like invalid tokens.
* @param array|null $responseData
* @param mixed $notifiable
*/
protected function handleExpoErrors(?array $responseData, $notifiable): void
{
if (!isset($responseData['data']) || !is_array($responseData['data'])) {
return;
}
$tokensToRemove = [];
foreach ($responseData['data'] as $index => $ticket) {
if (isset($ticket['status']) && $ticket['status'] === 'error') {
Log::warning('Expo Push Ticket Error:', [
'user_id' => $notifiable->id,
'ticket' => $ticket
]);
// Check if the error indicates an invalid token
if (isset($ticket['details']['error']) && $ticket['details']['error'] === 'DeviceNotRegistered') {
// Need to find the original token sent at this index
// This requires careful mapping if you modified the order or filtered tokens
// Assuming $payloads was created in the same order as $tokens initially
// $originalTokens = $notifiable->routeNotificationFor('Expo', null); // Re-fetch or pass $tokens
// $tokenToRemove = $originalTokens[$index] ?? null;
// if ($tokenToRemove) $tokensToRemove[] = $tokenToRemove;
// Simpler (if payload index matches original token index):
// Fetch original payloads from the send method if possible, or assume index matches
// This part is tricky without passing the original token map
// For now, log the error. Robust solution requires mapping sent 'to' token back.
Log::error("Expo token potentially invalid for user {$notifiable->id}. Consider implementing token removal.", ['ticket' => $ticket]);
}
}
}
// if (!empty($tokensToRemove)) {
// Log::info("Removing invalid Expo tokens for user {$notifiable->id}:", ['tokens' => $tokensToRemove]);
// $notifiable->devices()->whereIn('expo_push_token', $tokensToRemove)->delete();
// }
}
}
Register the Channel: You don't explicitly register custom channels like drivers. You just use the class name string ExpoChannel::class in the via() method of your notifications.
// app/Http/Controllers/Api/NotificationController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
class NotificationController extends Controller
{
public function index(Request $request): JsonResponse
{
$user = Auth::user();
$limit = $request->query('limit', 15); // Paginate results
$notifications = $user->notifications()->paginate($limit); // Fetches database notifications
return response()->json($notifications);
}
public function unreadCount(): JsonResponse
{
$user = Auth::user();
$count = $user->unreadNotifications()->count();
return response()->json(['unread_count' => $count]);
}
public function markAsRead(Request $request): JsonResponse
{
$user = Auth::user();
$validated = $request->validate([
'ids' => 'required|array',
'ids.*' => 'string|exists:notifications,id', // Ensure IDs exist and belong to user (implicitly checked)
]);
$user->unreadNotifications()
->whereIn('id', $validated['ids'])
->update(['read_at' => now()]);
return response()->json(['message' => 'Notifications marked as read.']);
}
public function markAllRead(): JsonResponse
{
$user = Auth::user();
$user->unreadNotifications()->update(['read_at' => now()]);
return response()->json(['message' => 'All notifications marked as read.']);
}
}
Implement UserDeviceController: (Handles registering Expo tokens from the client app)
php
// app/Http/Controllers/Api/UserDeviceController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\UserDevice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
class UserDeviceController extends Controller
{
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'expo_push_token' => 'required|string|unique:user_devices,expo_push_token', // Ensure token is unique globally
'device_info' => 'nullable|string|max:500',
]);
$user = Auth::user();
$device = $user->devices()->updateOrCreate(
['expo_push_token' => $validated['expo_push_token']], // Find or create by token
['device_info' => $validated['device_info'] ?? null, 'last_used_at' => now()] // Update info/timestamp
);
return response()->json(['message' => 'Device registered successfully.', 'data' => $device], 201);
}
public function destroy(Request $request, string $token): JsonResponse
{
// URL decode the token if necessary, depending on how client sends it
$token = urldecode($token);
$user = Auth::user();
$deletedCount = $user->devices()->where('expo_push_token', $token)->delete();
if ($deletedCount > 0) {
return response()->json(['message' => 'Device token removed successfully.']);
} else {
return response()->json(['message' => 'Device token not found for this user.'], 404);
}
}
}