Complex Notification Service in Laravel
Overview
The following is a high-level implementation of a complex notification service in Laravel that supports multiple user types, notification types, and delivery channels.
Step 1: Define User Types and Notification Types
First, we need to define the different user types and notification types.
User Types
- Tenants (business owners)
- Staff (assigned to tasks/appointments)
- Customers (clients booking appointments)
Notification Types
- Appointment updates (assigned, changed, reminders)
- Invoice created
- Messages or internal comments
- System alerts or reminders
Step 2: Create the Notification Model and Migration
Create a new migration for the notifications table.
// database/migrations/2023_12_01_000000_create_notifications_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateNotificationsTable extends Migration
{
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->id();
$table->string('type');
$table->morphs('notifiable');
$table->text('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('notifications');
}
}
Run the migration to create the notifications table.
php artisan migrate
Step 3: Create the Notification Service
Create a new service class that will handle the notification logic.
// app/Services/NotificationService.php
namespace App\Services;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Support\Facades\Notification as LaravelNotification;
class NotificationService
{
public function sendNotification(User $user, $notificationType, $data)
{
// Create a new notification instance
$notification = new Notification();
$notification->type = $notificationType;
$notification->notifiable()->associate($user);
$notification->data = $data;
$notification->save();
// Send the notification via the desired channels
$this->sendViaChannels($user, $notification);
}
private function sendViaChannels(User $user, Notification $notification)
{
// Check the user's preferred notification channels
$channels = $user->notification_channels;
// Send the notification via each channel
foreach ($channels as $channel) {
switch ($channel) {
case 'email':
$this->sendViaEmail($user, $notification);
break;
case 'push':
$this->sendViaPush($user, $notification);
break;
case 'in-app':
// In-app notifications are already handled by the database
break;
default:
// Handle unknown channels
break;
}
}
}
private function sendViaEmail(User $user, Notification $notification)
{
// Send the notification via email using Laravel's notification system
LaravelNotification::send($user, new \App\Notifications\GenericNotification($notification));
}
private function sendViaPush(User $user, Notification $notification)
{
// Send the notification via push using Expo
// Implement the Expo push notification logic here
// For example:
$expo = new \ExponentPhp\Expo();
$token = $user->expo_push_token;
$message = [
'to' => $token,
'title' => 'New Notification',
'body' => $notification->data,
];
$expo->send($message);
}
}
Step 4: Create the Notification Types and Channels
Create new classes for each notification type.
// app/Notifications/AppointmentUpdateNotification.php
namespace App\Notifications;
use App\Models\Notification;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification as LaravelNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
class AppointmentUpdateNotification extends LaravelNotification implements ShouldQueue
{
use Queueable;
private $notification;
public function __construct(Notification $notification)
{
$this->notification = $notification;
}
public function via($notifiable)
{
return ['mail', 'database'];
}
public function toMail($notifiable)
{
return (new \Illuminate\Mail\Message())
->subject('Appointment Update')
->line($this->notification->data);
}
public function toArray($notifiable)
{
return [
'data' => $this->notification->data,
];
}
}
Step 5: Implement the Notification Logic
Use the notification service to send notifications.
// app/Http/Controllers/AppointmentController.php
namespace App\Http\Controllers;
use App\Services\NotificationService;
use App\Models\Appointment;
use App\Models\User;
class AppointmentController extends Controller
{
private $notificationService;
public function __construct(NotificationService $notificationService)
{
$this->notificationService = $notificationService;
}
public function update(Appointment $appointment)
{
// Update the appointment logic here
// Send a notification to the assigned staff member
$staffMember = $appointment->staff;
$this->notificationService->sendNotification($staffMember, 'appointment_update', 'Appointment updated');
// Send a notification to the customer
$customer = $appointment->customer;
$this->notificationService->sendNotification($customer, 'appointment_update', 'Appointment updated');
}
}
Example Use Cases
- Send a notification to a staff member when an appointment is assigned to them.
- Send a notification to a customer when an appointment is updated or cancelled.
- Send a notification to a tenant when a new invoice is created.
Advice
- Make sure to handle the different user types and notification types correctly.
- Use Laravel's built-in notification system to simplify the notification logic.
- Consider using a queue to handle the notification sending to avoid blocking the main request.
- Implement the Expo push notification logic according to their documentation.
Future Improvements
- Add support for SMS notifications.
- Implement a notification preferences system to allow users to customize their notification settings.
- Use a more robust notification system that can handle a large volume of notifications.