shiftechafrica/laravel-notification
Installation
composer require shiftechafrica/laravel-notification
php artisan vendor:publish --provider="ShiftechAfrica\Notification\NotificationServiceProvider"
database/migrations/ and config/notification.php.Run Migrations
php artisan migrate
notifications table for storing system notifications.First Use Case: Sending a Notification
use ShiftechAfrica\Notification\Facades\Notification;
// Send a notification to a user
Notification::send(
userId: 1, // Target user ID
title: 'Account Update Required',
message: 'Your account details need verification.',
type: 'info', // 'info', 'warning', 'error', 'success'
data: ['key' => 'value'] // Optional additional data
);
Displaying Notifications
@notifications in your layout:
@notifications
@foreach($notifications as $notification)
<div class="alert alert-{{ $notification->type }}">
<strong>{{ $notification->title }}</strong>
<p>{{ $notification->message }}</p>
@if($notification->data)
<pre>{{ json_encode($notification->data) }}</pre>
@endif
</div>
@endforeach
@endnotifications
Basic Usage
Notification::send($userId, $title, $message, $type, $data = []);
$type: Must be one of ['info', 'warning', 'error', 'success'].$data: Serialized as JSON in the database.Bulk Notifications
Notification::sendToUsers(
userIds: [1, 2, 3],
title: 'System Alert',
message: 'Maintenance scheduled tomorrow.',
type: 'warning'
);
Conditional Notifications
if ($user->hasUnreadNotifications()) {
Notification::send($user->id, 'New Message', 'You have 3 unread messages.', 'info');
}
Notification::markAsRead($userId, $notificationId);
Notification::delete($userId, $notificationId);
Notification::markAllAsRead($userId); // Marks all notifications for a user as read
$unread = Notification::getUnread($userId);
$notifications = Notification::getAll($userId, 10); // Limit 10 per page
$errors = Notification::getByType($userId, 'error');
Extend Notification Model
Override the ShiftechAfrica\Notification\Models\Notification model in app/Models/Notification.php:
namespace App\Models;
use ShiftechAfrica\Notification\Models\Notification as BaseNotification;
class Notification extends BaseNotification {
protected $casts = [
'data' => 'array', // Auto-cast data to array
];
}
Custom Views
Publish the views and override them in resources/views/vendor/notification/:
php artisan vendor:publish --tag=notification-views
Trigger notifications from Laravel events:
use ShiftechAfrica\Notification\Facades\Notification;
class UserRegistered implements ShouldBroadcast {
public function broadcast(ShouldBroadcast $event) {
Notification::send(
$event->user->id,
'Welcome!',
'Your account has been created.',
'success'
);
}
}
Add middleware to check for unread notifications:
namespace App\Http\Middleware;
use Closure;
use ShiftechAfrica\Notification\Facades\Notification;
class CheckNotifications {
public function handle($request, Closure $next) {
if (auth()->check() && Notification::hasUnread(auth()->id())) {
// Redirect or show a badge
}
return $next($request);
}
}
Return notifications in API responses:
return response()->json([
'data' => $user,
'unread_notifications' => Notification::getUnread($user->id),
]);
Use Laravel Echo to update notifications in real-time:
Echo.channel('user.notifications')
.listen('NotificationSent', (e) => {
// Update UI dynamically
});
Type Validation
$type parameter must be one of ['info', 'warning', 'error', 'success']. Passing invalid types will throw an exception.Notification::send():
$validTypes = ['info', 'warning', 'error', 'success'];
if (!in_array($type, $validTypes)) {
throw new \InvalidArgumentException("Invalid notification type.");
}
Data Serialization
$data field is stored as JSON in the database. Ensure your data is JSON-serializable (no resources or non-serializable objects).json_encode() or cast the field in your model:
protected $casts = ['data' => 'array'];
User Existence
$userId exists. Passing a non-existent user ID will create a notification but may cause issues elsewhere.if (!User::find($userId)) {
throw new \InvalidArgumentException("User does not exist.");
}
Migration Conflicts
notifications table manually, future migrations may fail. Always extend migrations via:
php artisan make:migration extend_notifications_table --table=notifications
Log Failed Notifications Add logging to track issues:
Notification::send($userId, $title, $message, $type, $data);
// Log the call for debugging
\Log::info('Notification sent', [
'user_id' => $userId,
'title' => $title,
'type' => $type,
]);
Check Database Directly Verify notifications are stored correctly:
SELECT * FROM notifications WHERE user_id = 1;
Disable Queue for Testing Temporarily disable queues to test notifications immediately:
Notification::setQueue(false); // Disables queue usage
Custom Notification Channels Extend the package to support additional channels (e.g., SMS, email):
// app/Providers/NotificationServiceProvider.php
public function boot() {
Notification::extend('sms', function ($app) {
return new class {
public function send($userId, $message) {
// Logic to send SMS
}
};
});
}
Notification::channel('sms')->send($userId, 'Your code: 1234');
Notification Policies Add policies to control who can send/notifications:
use ShiftechAfrica\Notification\Contracts\NotificationPolicy;
class AdminNotificationPolicy implements NotificationPolicy {
public function canSend($user, $notification) {
return $user->isAdmin();
}
}
config/notification.php:
'policies' => [
'admin' => \App\Policies\AdminNotificationPolicy::class,
],
Notification::send($userId, 'Alert', 'Message.', 'warning', [], 'admin');
Custom Storage Override the storage engine (e.g., Redis, DynamoDB):
Notification::setStorage(function () {
return new \App\Services\RedisNotification
How can I help you explore Laravel packages today?