Multilingual Notification System Documentation

📄 General
← Back to Documentation
# Multilingual Notification System Documentation ## 🌍 **Complete Multilingual Notification Implementation** ### **📖 Overview** A comprehensive multilingual notification system that automatically detects user locale preferences and sends notifications in the correct language. The system supports English and Bulgarian with easy extensibility for additional languages. --- ## 🏗️ **System Architecture** ### **Core Components** 1. **NotificationTemplateHelper** - Template management with multilingual support 2. **MultilingualNotificationService** - Service layer for sending localized notifications 3. **SetNotificationLocale Middleware** - Automatic locale detection and setting 4. **Multilingual Seeder** - Database seeding with translated templates 5. **TemplateNotification** - Generic notification class for template-based content --- ## 🌐 **Supported Languages** ### **Current Languages** - **English (en)** - Default language - **Bulgarian (bg)** - Full translation support ### **Adding New Languages** ```php // config/app.php 'supported_locales' => [ 'en' => 'English', 'bg' => 'Български', 'de' => 'Deutsch', // Add German 'fr' => 'Français', // Add French 'es' => 'Español', // Add Spanish ], ``` --- ## 📧 **Template Structure** ### **Multilingual Template Format** ```json { "translations": { "en": { "subject": "Booking Confirmation - #{booking_number}", "content": "Dear {customer_name},\n\nThank you for your booking..." }, "bg": { "subject": "Потвърждение на резервация - #{booking_number}", "content": "Уважаеми/а {customer_name},\n\nБлагодарим Ви за резервацията..." } } } ``` ### **Template Variables** - `{customer_name}` - Customer's full name - `{booking_number}` - Unique booking identifier - `{venue_name}` - Name of the venue - `{company_name}` - Your company name - `{booking_date}` - Booking date - `{booking_time}` - Booking time - `{payment_amount}` - Payment amount - `{verification_code}` - Email verification code - `{reset_url}` - Password reset link --- ## 🚀 **Usage Examples** ### **Basic Usage** ```php use App\Services\MultilingualNotificationService; // Send to single user with automatic locale detection MultilingualNotificationService::sendToUser( $user, BookingConfirmationNotification::class, ['booking' => $booking] ); // Send template-based notification MultilingualNotificationService::sendTemplateBased( $user, 'booking_confirmation_template', [ 'customer_name' => $user->name, 'booking_number' => $booking->booking_number, 'venue_name' => $booking->venue->name, ] ); ``` ### **Advanced Usage** ```php // Send to multiple users with individual locale detection $results = MultilingualNotificationService::sendToMultiple( $users, PromotionalOfferNotification::class, ['offer' => $offer] ); // Send with explicit locale override MultilingualNotificationService::sendToUser( $user, WelcomeEmailNotification::class, [], 'bg' // Force Bulgarian regardless of user preference ); // Get localized template content $template = MultilingualNotificationService::getLocalizedTemplate( 'welcome_email_template', ['customer_name' => $user->name], $user ); ``` ### **Convenience Methods** ```php // Send welcome email MultilingualNotificationService::sendWelcomeEmail($user, [ 'venues_url' => route('venues.index'), 'booking_url' => route('bookings.create'), ]); // Send booking confirmation MultilingualNotificationService::sendBookingConfirmation($user, $booking, [ 'duration' => '2 hours', 'total_amount' => '$100', ]); ``` --- ## 🔧 **Configuration** ### **App Configuration** ```php // config/app.php return [ 'locale' => 'en', // Default application locale 'fallback_locale' => 'en', // Fallback locale 'supported_locales' => [ // Available locales 'en' => 'English', 'bg' => 'Български', ], ]; ``` ### **Middleware Registration** ```php // app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ // ... other middleware \App\Http\Middleware\SetNotificationLocale::class, ], ]; ``` --- ## 🗄️ **Database Setup** ### **Run the Seeder** ```bash # Seed multilingual templates php artisan db:seed --class=NotificationContentSeeder # Fresh database with all seeders php artisan migrate:fresh --seed ``` ### **Template Storage** ```sql -- Templates stored in settings table CREATE TABLE settings ( id BIGINT PRIMARY KEY, name VARCHAR(255), -- Template key group VARCHAR(255), -- 'notifications' payload JSON, -- Multilingual template data company_id BIGINT, -- Multi-tenant support active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP, updated_at TIMESTAMP ); ``` --- ## 🎯 **Locale Detection Priority** ### **Priority Order** 1. **Explicit Locale** - Passed directly to function 2. **User Preference** - User's saved locale setting 3. **Session Locale** - Set by middleware from browser 4. **App Locale** - Current application locale 5. **Fallback Locale** - Default fallback (English) ### **Automatic Detection** ```php // Middleware automatically detects from: // 1. User's saved preference // 2. Accept-Language browser header // 3. Session storage // 4. Application defaults ``` --- ## 📱 **Integration Examples** ### **In Controllers** ```php class BookingController extends Controller { public function confirm(Request $request, Booking $booking) { // Process booking confirmation // Send localized confirmation MultilingualNotificationService::sendBookingConfirmation( $request->user(), $booking ); return redirect()->route('bookings.show', $booking); } } ``` ### **In Notification Classes** ```php class BookingConfirmationNotification extends Notification { public function __construct(private Booking $booking) {} public function toMail($notifiable) { // Get localized template $template = MultilingualNotificationService::getLocalizedTemplate( 'booking_confirmation_template', [ 'customer_name' => $notifiable->name, 'booking_number' => $this->booking->booking_number, 'venue_name' => $this->booking->venue->name, 'booking_date' => $this->booking->date->format('Y-m-d'), 'booking_time' => $this->booking->time, 'company_name' => config('app.name'), ], $notifiable ); return (new MailMessage) ->subject($template['subject']) ->markdown('emails.custom', ['content' => $template['content']]); } } ``` ### **User Locale Management** ```php class UserController extends Controller { public function updateLocale(Request $request) { $request->validate([ 'locale' => 'required|in:en,bg' ]); $updated = MultilingualNotificationService::updateUserLocalePreference( $request->user(), $request->locale ); return response()->json(['success' => $updated]); } public function getCurrentLocale(Request $request) { $locale = MultilingualNotificationService::getUserNotificationLocale( $request->user() ); return response()->json(['locale' => $locale]); } } ``` --- ## 🎨 **Frontend Integration** ### **Language Switcher** ```blade <!-- resources/views/components/language-switcher.blade.php --> <div class="language-switcher"> <form action="{{ route('user.update-locale') }}" method="POST"> @csrf <select name="locale" onchange="this.form.submit()"> @foreach(config('app.supported_locales') as $code => $name) <option value="{{ $code }}" {{ Auth::user()->locale === $code ? 'selected' : '' }}> {{ $name }} </option> @endforeach </select> </form> </div> ``` ### **JavaScript Integration** ```javascript // Send notification with locale preference async function sendNotification(userId, templateKey, variables) { try { const response = await fetch('/api/notifications/send', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept-Language': navigator.language || 'en' }, body: JSON.stringify({ user_id: userId, template: templateKey, variables: variables }) }); return await response.json(); } catch (error) { console.error('Failed to send notification:', error); } } ``` --- ## 🔍 **Testing & Debugging** ### **Preview Templates** ```php // Preview template in different languages $enPreview = MultilingualNotificationService::previewNotification( 'booking_confirmation_template', ['customer_name' => 'John Doe'], 'en' ); $bgPreview = MultilingualNotificationService::previewNotification( 'booking_confirmation_template', ['customer_name' => 'Иван Иванов'], 'bg' ); ``` ### **Logging** ```php // All notification activities are logged Log::info("Multilingual notification sent", [ 'notification_class' => $notificationClass, 'locale' => $locale, 'notifiable_type' => get_class($notifiable), 'notifiable_id' => $notifiable->id, ]); ``` ### **Debug Mode** ```php // Enable debug mode for detailed logging if (config('app.debug')) { // Log template resolution process // Log locale detection steps // Log variable replacement } ``` --- ## 📊 **Monitoring & Analytics** ### **Notification Statistics** ```php // Track notification usage by locale $stats = DB::table('notifications') ->selectRaw('locale, COUNT(*) as count') ->where('created_at', '>=', now()->subDays(30)) ->groupBy('locale') ->get(); // Results: // [ // ['locale' => 'en', 'count' => 1250], // ['locale' => 'bg', 'count' => 890], // ] ``` ### **User Preference Analytics** ```php // Analyze user locale preferences $localePreferences = User::selectRaw('locale, COUNT(*) as user_count') ->whereNotNull('locale') ->groupBy('locale') ->get(); ``` --- ## 🛠 **Maintenance & Updates** ### **Adding New Templates** ```php // 1. Add to seeder 'new_template_key' => [ 'translations' => [ 'en' => [ 'subject' => 'New Template Subject', 'content' => 'English content...' ], 'bg' => [ 'subject' => 'Нов шаблон предмет', 'content' => 'Българско съдържание...' ], ], ], // 2. Update NotificationTemplateHelper::getAvailableTemplates() // 3. Run seeder to update database ``` ### **Updating Translations** ```bash # Update specific template php artisan db:seed --class=NotificationContentSeeder # Or update manually through admin panel ``` ### **Quality Assurance** ```php // Validate all templates have required translations $missingTranslations = []; $templates = NotificationTemplateHelper::getAvailableTemplates(); $locales = config('app.supported_locales'); foreach ($templates as $template) { $content = setting($template, 'notifications'); $translations = json_decode($content, true)['translations'] ?? []; foreach ($locales as $locale => $name) { if (!isset($translations[$locale])) { $missingTranslations[] = "{$template} missing {$locale}"; } } } ``` --- ## 🎯 **Best Practices** ### **Performance Optimization** - **Template Caching** - Cache parsed templates - **Batch Processing** - Send notifications in batches - **Queue Management** - Use queues for high-volume notifications - **Lazy Loading** - Load translations only when needed ### **User Experience** - **Consistent Language** - Maintain same language across all touchpoints - **Respect Preferences** - Honor user's language choices - **Graceful Fallbacks** - Always provide content in fallback language - **Clear Communication** - Use language-appropriate tone and style ### **Development Practices** - **Consistent Variable Names** - Use same variables across templates - **Complete Translations** - Ensure all languages have complete content - **Regular Testing** - Test all language variations - **Documentation** - Keep translation guidelines updated --- ## 🚨 **Troubleshooting** ### **Common Issues** ```php // Issue: Template not found // Solution: Check template key and run seeder if (!NotificationTemplateHelper::templateExists($templateKey)) { Log::error("Template not found: {$templateKey}"); } // Issue: Wrong language sent // Solution: Verify user locale and detection logic $detectedLocale = MultilingualNotificationService::getUserNotificationLocale($user); Log::info("Detected locale for user {$user->id}: {$detectedLocale}"); // Issue: Variables not replaced // Solution: Check variable names and template format $template = NotificationTemplateHelper::getTemplate($templateKey, $variables); Log::debug("Template result", $template); ``` ### **Debug Commands** ```bash # Check seeded templates php artisan tinker >>> setting('booking_confirmation_template', 'notifications'); # Test locale detection php artisan tinker >>> app(App\Services\MultilingualNotificationService::class) ->getUserNotificationLocale(User::find(1)); ``` --- ## 🎉 **Benefits** ### **For Users** - **Native Language Experience** - Receive notifications in preferred language - **Better Understanding** - Improved comprehension and engagement - **Cultural Relevance** - Content adapted to cultural context - **Personalized Experience** - Respects individual preferences ### **For Business** - **Higher Engagement** - Users more likely to read and act on notifications - **Better Conversion** - Improved response rates in native languages - **Global Reach** - Easy expansion to new markets - **Customer Satisfaction** - Enhanced user experience ### **For Developers** - **Easy Implementation** - Simple API for sending localized notifications - **Maintainable Code** - Centralized template management - **Scalable Architecture** - Easy to add new languages - **Comprehensive Tools** - Complete testing and debugging support --- **This multilingual notification system provides a complete solution for sending personalized, localized notifications that automatically adapt to user preferences while maintaining high performance and ease of use!** 🌍✨