Sitemap

Laravel Notification Sistemi

3 min readNov 5, 2024

Laravel Notification sistemini detaylıca inceleyelim:

1. Notification Nedir?

  • Kullanıcılara bildirim göndermek için kullanılan sınıflardır
  • Birden fazla kanaldan bildirim göndermeyi sağlar (mail, SMS, Slack, database vb.)
  • Tek bir bildirim sınıfı ile farklı kanallara bildirim gönderilebilir

2. Ne Zaman Kullanılır?

Örnek senaryolar:

- Kullanıcı kaydı onayı
- Şifre sıfırlama bildirimi
- Sipariş durumu güncellemesi
- Ödeme bildirimleri
- Sistem uyarıları
- Yeni mesaj bildirimleri

3. Notification Oluşturma ve Yapısı:

a) Notification Oluşturma:

# Notification oluşturma
php artisan make:notification InvoicePaid

b) Temel Notification Yapısı:

class InvoicePaid extends Notification
{
use Queueable;

private $invoice;

public function __construct(Invoice $invoice)
{
$this->invoice = $invoice;
}

// Hangi kanallardan gönderileceği
public function via($notifiable)
{
return ['mail', 'database', 'slack'];
}

// Mail için içerik
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Fatura Ödendi')
->line('Faturanız başarıyla ödendi.')
->action('Faturayı Görüntüle', url('/invoices/'.$this->invoice->id))
->line('Teşekkür ederiz!');
}

// Database için data
public function toDatabase($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}

// Slack için mesaj
public function toSlack($notifiable)
{
return (new SlackMessage)
->success()
->content('Fatura ödendi: '.$this->invoice->amount);
}
}

4. Notification Gönderme Yöntemleri:

a) Tek Kullanıcıya Bildirim:

// Direkt Notification facade ile
Notification::send($user, new InvoicePaid($invoice));

// Model üzerinden
$user->notify(new InvoicePaid($invoice));

// Gecikmeli bildirim
$user->notify((new InvoicePaid($invoice))->delay(now()->addMinutes(10)));

b) Çoklu Kullanıcıya Bildirim:

// Birden fazla kullanıcıya
Notification::send(User::all(), new InvoicePaid($invoice));

// Belirli bir role sahip kullanıcılara
Notification::send(
User::role('admin')->get(),
new SystemAlert($message)
);

c) On-Demand Notifications:

// Email adresine direkt gönderim
Notification::route('mail', 'test@example.com')
->notify(new InvoicePaid($invoice));

// Slack webhook'una gönderim
Notification::route('slack', 'webhook-url')
->notify(new ServerDown($server));

5. Notification Kanalları ve Özelleştirme:

a) Mail Channel:

public function toMail($notifiable)
{
return (new MailMessage)
->subject('Hoşgeldiniz')
->greeting('Merhaba '.$notifiable->name)
->line('Hesabınız başarıyla oluşturuldu.')
->action('Profili Görüntüle', url('/profile'))
->line('Teşekkür ederiz!')
->priority(1) // Yüksek öncelik
->attach('/path/to/file') // Dosya ekleme
->markdown('notifications.welcome'); // Özel template
}

b) Database Channel:

// Migration oluşturma
php artisan notifications:table

// Database datası
public function toDatabase($notifiable)
{
return [
'message' => 'Yeni bir mesajınız var',
'sender_id' => auth()->id(),
'type' => 'message',
'read_at' => null
];
}

c) Slack Channel:

public function toSlack($notifiable)
{
return (new SlackMessage)
->success()
->content('Yeni sipariş alındı!')
->attachment(function ($attachment) {
$attachment->title('Sipariş #123')
->fields([
'Müşteri' => $this->order->customer->name,
'Tutar' => $this->order->amount
]);
});
}

6. Notification Customization:

a) Özel Kanal Oluşturma:

class SmsChannel
{
protected $smsService;

public function __construct(SmsService $smsService)
{
$this->smsService = $smsService;
}

public function send($notifiable, Notification $notification)
{
$message = $notification->toSms($notifiable);

$this->smsService->send(
$notifiable->phone_number,
$message
);
}
}

b) Özel Template:

// resources/views/notifications/order-shipped.blade.php
@component('mail::message')
# Siparişiniz Kargoya Verildi

Sipariş numarası: {{ $order->number }}

@component('mail::button', ['url' => $url])
Siparişi Takip Et
@endcomponent

Teşekkürler,<br>
{{ config('app.name') }}
@endcomponent

7. Notification Yönetimi:

a) Okundu/Okunmadı İşaretleme:

// Tek bildirimi okundu yapma
$user->notifications()->find($id)->markAsRead();

// Tüm bildirimleri okundu yapma
$user->unreadNotifications->markAsRead();

// Belirli bildirimleri okundu yapma
$user->unreadNotifications
->where('type', InvoicePaid::class)
->markAsRead();

b) Bildirim Sorgulama:

// Okunmamış bildirimler
$user->unreadNotifications;

// Tüm bildirimler
$user->notifications;

// Belirli tip bildirimler
$user->notifications()
->where('type', InvoicePaid::class)
->get();

8. Queue Kullanımı:

class InvoicePaid extends Notification implements ShouldQueue
{
use Queueable;

public $tries = 3; // Deneme sayısı
public $timeout = 60; // Zaman aşımı

public function failed($exception)
{
// Hata durumu yönetimi
}
}

9. Testing:

class NotificationTest extends TestCase
{
public function test_invoice_paid_notification()
{
Notification::fake();

$user = User::factory()->create();
$invoice = Invoice::factory()->create();

$user->notify(new InvoicePaid($invoice));

// Bildirimin gönderildiğini kontrol
Notification::assertSentTo(
$user,
InvoicePaid::class,
function ($notification, $channels) use ($invoice) {
return $notification->invoice->id === $invoice->id;
}
);

// Mail içeriğini kontrol
Notification::assertSentTo(
$user,
InvoicePaid::class,
function ($notification, $channels) {
return in_array('mail', $channels);
}
);
}
}

10. Best Practices:

Channel Seçimi:

public function via($notifiable)
{
// Kullanıcı tercihlerine göre kanal seçimi
return $notifiable->notification_preferences ?? ['mail'];

// Koşullu kanal seçimi
return array_filter([
'mail' => $notifiable->email,
'sms' => $notifiable->phone,
'slack' => $notifiable->slack_webhook,
]);
}

Error Handling:

try {
$user->notify(new InvoicePaid($invoice));
} catch (Exception $e) {
Log::error('Notification failed', [
'user' => $user->id,
'error' => $e->getMessage()
]);
}

Localization:

public function toMail($notifiable)
{
return (new MailMessage)
->subject(__('notifications.invoice.subject'))
->line(__('notifications.invoice.paid', [
'amount' => $this->invoice->amount
]));
}

--

--

No responses yet