Okay, let's build a robust and complex notification service in Laravel. This will involve setting up models, notifications, channels, events, listeners, and API endpoints.
Assumptions:
You have a working Laravel >= 8.x project set up.
You have user authentication in place.
You have models like Tenant, Staff, Customer, Appointment, Invoice, Message. (We'll create basic versions if needed).
You're familiar with basic Laravel concepts (Eloquent, Migrations, Queues, Events).
You have Node.js/NPM/Yarn for installing Expo dependencies if needed for testing push notifications locally.
Steps:
Models & Notifiable Trait: Ensure your user-type models implement Notifiable.
Install Necessary Packages: Add the Expo channel package.
Configuration: Set up .env and config files for Mail and Expo.
Migrations: Add fields for push tokens, phone numbers (optional), and run the notifications table migration.
Notification Classes: Create specific notification classes for each event type.
Channels Implementation: Implement toMail, toDatabase, toExpoPush methods in notifications.
Routing Notifications: Implement routeNotificationFor... methods on your Notifiable models.
Events & Listeners: Decouple notification sending using events.
Triggering Notifications: Fire events from your application logic.
In-App Notification API: Create endpoints to fetch and manage notifications.
Queueing: Ensure notifications are queued for performance.
Tenant Scoping: Consider how to scope notifications correctly in a multi-tenant app.
1. Models & Notifiable Trait
Ensure your Tenant, Staff, and Customer models (or a base User model if they share one) use the Notifiable trait.
php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable; // Or your base Model
use Illuminate\Notifications\Notifiable;
// Potentially add tenant scoping traits if you have them
// use App\Traits\BelongsToTenant;
class Tenant extends Authenticatable // Or Model
{
use HasFactory, Notifiable; //, BelongsToTenant;
// ... other model properties, relationships
/**
* Get the Expo push notification routing information for the tenant.
* Assumes a single token per tenant for simplicity, adjust if needed.
*
* @return string|array|null
*/
public function routeNotificationForExpoPush()
{
// Fetch the token from a related profile, settings, or a dedicated column
return $this->expo_push_token;
}
/**
* Get the email address for mailing notifications.
*/
public function routeNotificationForMail($notification)
{
return $this->email;
}
// Add routeNotificationForVonage() if implementing SMS later
}
class Staff extends Authenticatable // Or Model
{
use HasFactory, Notifiable; //, BelongsToTenant; // Staff likely belong to a Tenant
// ... other model properties, relationships (e.g., belongsTo Tenant)
public function routeNotificationForExpoPush()
{
// Example: Fetch token(s) from a related device table or a column
// If a staff member can have multiple devices:
// return $this->devices()->pluck('expo_push_token')->toArray();
return $this->expo_push_token;
}
public function routeNotificationForMail($notification)
{
return $this->email;
}
}
class Customer extends Authenticatable // Or Model
{
use HasFactory, Notifiable; //, BelongsToTenant; // Customers might belong to a Tenant
// ... other model properties, relationships
public function routeNotificationForExpoPush()
{
return $this->expo_push_token;
}
public function routeNotificationForMail($notification)
{
return $this->email;
}
}
.env: Configure Mail driver and credentials. Add Expo Access Token.
dotenv
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
# Get this from your Expo account (Project -> Settings -> Access Tokens)
EXPO_ACCESS_TOKEN=your_expo_access_token_here
# Ensure Queue Connection is not 'sync' for production/testing queues
QUEUE_CONNECTION=database # Or redis, beanstalkd, sqs
config/services.php: Ensure Expo config is present (usually added automatically or after publishing).
config/broadcasting.php: (Optional, but good practice) Ensure your push notification connections are defined if you plan to use broadcasting features alongside notifications.
4. Migrations
Add Fields to User Tables: Add a nullable string column to store the Expo push token. You might need a more complex setup (like a separate user_devices table) if users can have multiple tokens.
// In the generated migration file (adjust for tenant, staff, customer tables)
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddExpoTokenToUsersTables extends Migration
{
public function up()
{
Schema::table('tenants', function (Blueprint $table) {
$table->string('expo_push_token')->nullable()->after('email');
});
Schema::table('staff', function (Blueprint $table) {
$table->string('expo_push_token')->nullable()->after('email');
});
Schema::table('customers', function (Blueprint $table) {
$table->string('expo_push_token')->nullable()->after('email');
});
}
public function down()
{
Schema::table('tenants', function (Blueprint $table) { $table->dropColumn('expo_push_token'); });
Schema::table('staff', function (Blueprint $table) { $table->dropColumn('expo_push_token'); });
Schema::table('customers', function (Blueprint $table) { $table->dropColumn('expo_push_token'); });
}
}
Notifications Table: Create the table to store database notifications.
Create Email Markdown Views: Create the corresponding markdown files (e.g., resources/views/emails/appointments/assigned.blade.php). Use Markdown Mail Components.
blade
{{-- resources/views/emails/appointments/assigned.blade.php --}}
@component('mail::message')
# New Appointment Assigned
Hi {{ $staffName }},
You have been assigned a new appointment:
**Customer:** {{ $customerName }}
**Service:** {{ $serviceName }}
**Time:** {{ $startTime }}
@if($assignerName)
Assigned by: {{ $assignerName }}
@endif
@component('mail::button', ['url' => $url])
View Appointment Details
@endcomponent
Thanks,<br>
{{ config('app.name') }}
@endcomponent
Implement Other Notifications: Create similar classes (InvoiceCreated, NewStaffMessage, SystemAlert) with appropriate via, toMail, toExpoPush, toArray methods, tailoring the content and recipients. For example, InvoiceCreated might notify a Customer and maybe a Tenant, while NewStaffMessage might notify specific Staff members within a Tenant context.
6. Channels Implementation (Covered in Step 5)
The via() method determines which channels are used. The toMail(), toDatabase(), toExpoPush() methods format the notification for each channel.
7. Routing Notifications (Covered in Step 1 & 5)
The routeNotificationFor{ChannelName} methods on your Tenant, Staff, Customer models tell Laravel where to send the notification for that specific channel (e.g., which email address, which Expo token).
Ensure your front-end (React Native/Expo app) registers the device token with your backend and saves it to the correct user's expo_push_token field when they log in or enable notifications. You'll need an API endpoint for this.
8. Events & Listeners
This is the recommended way to trigger notifications to keep your controllers/services clean.
Event Classes: Populate events with relevant data.
php
<?php
namespace App\Events;
use App\Models\Appointment;
use App\Models\Staff; // The staff member assigned
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class AppointmentAssignedToStaff
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public Appointment $appointment;
public Staff $staff;
public ?Staff $assigner; // Optional
public function __construct(Appointment $appointment, Staff $staff, ?Staff $assigner = null)
{
$this->appointment = $appointment;
$this->staff = $staff;
$this->assigner = $assigner;
}
}
Define Listeners:
bash
php artisan make:listener SendAppointmentAssignedNotification --event=AppointmentAssignedToStaff
php artisan make:listener SendInvoiceCreatedNotification --event=InvoiceGenerated
# ... and so on
Listener Classes: Implement the handle method to send the notification.
php
<?php
namespace App\Listeners;
use App\Events\AppointmentAssignedToStaff;
use App\Notifications\AppointmentAssigned as AppointmentAssignedNotification; // Use alias
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification; // Import facade
class SendAppointmentAssignedNotification implements ShouldQueue // Implement ShouldQueue here too
{
use InteractsWithQueue;
public function handle(AppointmentAssignedToStaff $event)
{
// The staff member to notify is available in the event
$staffToNotify = $event->staff;
// Send the notification
// Use the Notification Facade or the notify() method on the model
// $staffToNotify->notify(new AppointmentAssignedNotification($event->appointment, $event->assigner));
// Or:
Notification::send($staffToNotify, new AppointmentAssignedNotification($event->appointment, $event->assigner));
// You could also notify other related parties here if needed, e.g., the tenant owner
// if ($tenant = $staffToNotify->tenant) {
// $tenant->notify(new SomeOtherNotification(...));
// }
}
}
Register Events & Listeners: Map events to listeners in app/Providers/EventServiceProvider.php.
php
<?php
namespace App\Providers;
use App\Events\AppointmentAssignedToStaff;
use App\Events\InvoiceGenerated;
// ... other events
use App\Listeners\SendAppointmentAssignedNotification;
use App\Listeners\SendInvoiceCreatedNotification;
// ... other listeners
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
AppointmentAssignedToStaff::class => [
SendAppointmentAssignedNotification::class,
// Add other listeners for this event if needed
],
InvoiceGenerated::class => [
SendInvoiceCreatedNotification::class,
],
// ... other mappings
];
// ... boot method etc.
}
9. Triggering Notifications
Dispatch events from your application logic (e.g., Controllers, Services).
php
<?php
namespace App\Http\Controllers;
use App\Models\Appointment;
use App\Models\Staff;
use App\Events\AppointmentAssignedToStaff;
use Illuminate\Http\Request;
class AppointmentController extends Controller
{
public function assignStaff(Request $request, Appointment $appointment)
{
$request->validate(['staff_id' => 'required|exists:staff,id']);
$staff = Staff::findOrFail($request->staff_id);
$appointment->staff_id = $staff->id;
$appointment->save();
// Get the user who performed the action (optional)
$assigner = $request->user(); // Assuming the logged-in user is Staff/Tenant
// Fire the event
AppointmentAssignedToStaff::dispatch($appointment, $staff, $assigner); // Pass relevant data
return response()->json(['message' => 'Staff assigned successfully.']);
}
}
10. In-App Notification API
Create endpoints for the front-end (web or mobile) to fetch and manage notifications stored in the database.
Routes (routes/api.php):
php
use App\Http\Controllers\Api\NotificationController; // Create this controller
Route::middleware('auth:sanctum')->prefix('user')->group(function () { // Or your relevant auth guard
Route::get('/notifications', [NotificationController::class, 'index']);
Route::get('/notifications/unread-count', [NotificationController::class, 'unreadCount']);
Route::post('/notifications/mark-all-read', [NotificationController::class, 'markAllRead']);
Route::post('/notifications/{notificationId}/mark-read', [NotificationController::class, 'markAsRead']);
// Endpoint for frontend to register Expo Push Token
Route::post('/notifications/register-push-token', [NotificationController::class, 'registerPushToken']);
});
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Notifications\DatabaseNotification;
class NotificationController extends Controller
{
// Get all notifications (read and unread), paginated
public function index(Request $request)
{
$user = $request->user(); // Get authenticated user (Tenant, Staff, Customer)
$notifications = $user->notifications()->paginate(15);
return response()->json($notifications);
}
// Get count of unread notifications
public function unreadCount(Request $request) {
$user = $request->user();
return response()->json(['count' => $user->unreadNotifications()->count()]);
}
// Mark a specific notification as read
public function markAsRead(Request $request, $notificationId)
{
$user = $request->user();
$notification = $user->notifications()->find($notificationId);
if ($notification) {
$notification->markAsRead();
return response()->json(['message' => 'Notification marked as read.']);
}
return response()->json(['message' => 'Notification not found.'], 404);
}
// Mark all unread notifications as read
public function markAllRead(Request $request)
{
$user = $request->user();
$user->unreadNotifications->markAsRead();
return response()->json(['message' => 'All notifications marked as read.']);
}
// Register or update the Expo Push Token for the user
public function registerPushToken(Request $request)
{
$request->validate([
'token' => 'required|string',
// 'device_name' => 'nullable|string' // Optional: If storing multiple devices
]);
$user = $request->user();
$token = $request->input('token');
// Simple update on the user model
$user->expo_push_token = $token;
$user->save();
// If using a separate devices table:
// $user->devices()->updateOrCreate(
// ['device_id' => $request->input('device_id', $token)], // Need a unique ID per device
// ['expo_push_token' => $token, 'name' => $request->input('device_name')]
// );
return response()->json(['message' => 'Push token registered successfully.']);
}
}
11. Queueing
Ensure your queue worker is running: php artisan queue:work.
Using ShouldQueue on Notifications and Listeners ensures that sending emails or push notifications doesn't slow down the user's request.
Configure your queue driver (database, redis, sqs, etc.) in .env and run migrations if needed (php artisan queue:table).
12. Tenant Scoping
In a multi-tenant application, this is crucial:
Data Association: Ensure Staff, Customers, Appointments, Invoices, etc., are correctly associated with a Tenant (e.g., via tenant_id foreign keys).
Notification Context: When triggering events or directly sending notifications, make sure you are only selecting recipients belonging to the relevant tenant.
Listeners can check the tenant context from the event data (e.g., $event->appointment->tenant_id).
Queries for recipients should always include where('tenant_id', $currentTenantId).
Global Scopes: Consider using Laravel's Global Scopes to automatically apply tenant filtering to Eloquent queries for relevant models.
Database Notifications Table: The default notifications table has notifiable_type and notifiable_id. If you need to query notifications per tenant easily, you might consider:
Adding a tenant_id column to the notifications table (requires customizing the migration and potentially the notification model).
Querying through the notifiable relationship: Fetch the Tenant -> Fetch their Staff/Customers -> Fetch their notifications.
Further Considerations & Enhancements:
User Preferences: Allow users (Staff, Customers) to choose which notification types they receive on which channels (e.g., add boolean flags like notify_appointment_via_email, notify_message_via_push to the user model or a separate notification_preferences table). Modify the via() method in notifications to check these preferences.
SMS Channel: Integrate laravel-notification-channels/vonage or twilio package, add routeNotificationForVonage (returning phone number) to models, and implement toVonage methods in notifications.
Real-time In-App: Use Laravel Echo and Pusher/Soketi/Ably for real-time updates to the in-app notification list without needing manual refreshes. Broadcast database notifications.
Error Handling: Implement robust error handling for failed notifications (e.g., invalid Expo tokens, email bounces). Use failed queue jobs logging.
Throttling/Rate Limiting: Be mindful of API rate limits for push/SMS services.
Localization: Make notification messages translatable using Laravel's localization features.
Testing: Write feature and unit tests for your notification sending logic and API endpoints. Laravel provides helpful testing utilities for notifications and events.
This comprehensive setup provides a flexible and scalable notification system for your complex Laravel application. Remember to adapt the model names, relationships, and specific logic to your exact application structure.
<?php
namespace App\Notifications;
use App\Models\Appointment;
use App\Models\Staff;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Expo\ExpoChannel;
use NotificationChannels\Expo\ExpoMessage;
class AppointmentAssigned extends Notification implements ShouldQueue
{
use Queueable;
public Appointment $appointment;
public Staff $assigner; // Optional: Who assigned it
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(Appointment $appointment, ?Staff $assigner = null)
{
$this->appointment = $appointment;
$this->assigner = $assigner;
// Ensure relationship is loaded if needed later
$this->appointment->loadMissing(['customer', 'service']);
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable The entity being notified (Staff member in this case)
* @return array
*/
public function via($notifiable): array
{
// Define default channels. Could be customized per user later.
$channels = ['database', 'mail'];
// Only send push if the user has a token registered
if (!empty($notifiable->routeNotificationForExpoPush())) {
$channels[] = ExpoChannel::class;
}
// Potentially add SMS channel here based on user preferences/token
// if ($notifiable->prefersSms() && $notifiable->routeNotificationForVonage()) {
// $channels[] = VonageSmsChannel::class; // Assuming Vonage
// }
return $channels;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable): MailMessage
{
$customerName = $this->appointment->customer->name ?? 'Customer';
$serviceName = $this->appointment->service->name ?? 'Service';
$startTime = $this->appointment->start_time->format('M d, Y H:i'); // Format as needed
return (new MailMessage)
->subject('New Appointment Assigned')
->markdown('emails.appointments.assigned', [
'appointment' => $this->appointment,
'staffName' => $notifiable->name, // Name of the staff being notified
'customerName' => $customerName,
'serviceName' => $serviceName,
'startTime' => $startTime,
'assignerName' => $this->assigner?->name, // Optional
'url' => url('/staff/appointments/' . $this->appointment->id) // Example URL
]);
}
/**
* Get the Expo Push representation of the notification.
*
* @param mixed $notifiable
* @return ExpoMessage
*/
public function toExpoPush($notifiable): ExpoMessage
{
$customerName = $this->appointment->customer->name ?? 'Customer';
$startTime = $this->appointment->start_time->format('H:i');
return ExpoMessage::create()
->title('New Appointment Assigned!')
->body("You've been assigned an appointment with {$customerName} at {$startTime}.")
->subtitle($this->appointment->service->name ?? 'Appointment')
->priority('high') // 'default', 'normal', 'high'
->channelId('appointments') // Optional: Android Notification Channel ID
->badge(1) // Optional: iOS badge count
->data([ // Optional: Extra data for the app to handle
'appointment_id' => $this->appointment->id,
'type' => 'appointment_assigned',
'url' => '/appointments/' . $this->appointment->id // In-app deep link path
]);
// ->sound('default'); // Optional: 'default' or null
}
/**
* Get the array representation of the notification (for database storage).
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable): array
{
// Data to be stored in the `data` column of the `notifications` table
return [
'appointment_id' => $this->appointment->id,
'customer_name' => $this->appointment->customer->name ?? null,
'service_name' => $this->appointment->service->name ?? null,
'start_time' => $this->appointment->start_time->toIso8601String(),
'message' => "You have a new appointment assigned.", // Simple text for display
'icon' => 'calendar-check', // Optional: icon hint for UI
'url' => '/staff/appointments/' . $this->appointment->id // Example URL for web UI
];
}
}