Skip to content

Notifications

Giới thiệu (Introduction)

Laravel hỗ trợ gửi notifications qua nhiều kênh: email, SMS (Vonage), Slack, và lưu vào database. Notifications cũng có thể broadcast qua WebSocket cho giao diện realtime.

Thường thì notifications là messages ngắn, thông báo sự kiện cho users (ví dụ: hóa đơn mới, đơn hàng đã giao).

Tạo Notifications

bash
php artisan make:notification InvoicePaid

Class nằm trong app/Notifications.

Gửi Notifications (Sending)

Sử dụng Notifiable Trait

php
use App\Notifications\InvoicePaid;

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

Sử dụng Notification Facade

php
use Illuminate\Support\Facades\Notification;

Notification::send($users, new InvoicePaid($invoice));

// On-demand (không cần user)
Notification::route('mail', 'taylor@example.com')
    ->route('vonage', '5555555555')
    ->notify(new InvoicePaid($invoice));

Channels (Kênh gửi)

Mỗi notification class có method via xác định kênh:

php
public function via(object $notifiable): array
{
    return $notifiable->prefers_sms
        ? ['vonage']
        : ['mail', 'database'];
}

Queueing Notifications

Implement ShouldQueue:

php
use Illuminate\Contracts\Queue\ShouldQueue;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;
}

Mail Notifications

php
use Illuminate\Notifications\Messages\MailMessage;

public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
        ->greeting('Xin chào!')
        ->line('Bạn đã nhận được hóa đơn mới.')
        ->action('Xem hóa đơn', $url)
        ->line('Cảm ơn bạn đã sử dụng dịch vụ!');
}

Tùy chỉnh Sender / Recipient / Subject

php
public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
        ->from('barrett@example.com', 'Barrett Blair')
        ->subject('Thông báo hóa đơn')
        ->line('...');
}

Attachments

php
public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
        ->line('...')
        ->attach('/path/to/file');
}

Markdown Mail Notifications

bash
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
php
public function toMail(object $notifiable): MailMessage
{
    return (new MailMessage)
        ->markdown('mail.invoice.paid', [
            'url' => $this->url,
        ]);
}

Database Notifications

Prerequisites

bash
php artisan make:notifications-table
php artisan migrate

Formatting

php
public function toDatabase(object $notifiable): array
{
    return [
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
    ];
}

Truy cập Notifications

php
$user = App\Models\User::find(1);

foreach ($user->notifications as $notification) {
    echo $notification->type;        // Loại notification
    echo $notification->data;        // Array data
}

// Chỉ unread
foreach ($user->unreadNotifications as $notification) {
    // ...
}

Đánh dấu đã đọc

php
$user->unreadNotifications->markAsRead();

$notification->markAsRead();

Broadcast Notifications

php
public function toBroadcast(object $notifiable): BroadcastMessage
{
    return new BroadcastMessage([
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
    ]);
}

Lắng nghe phía Client

js
Echo.private(`App.Models.User.${userId}`)
    .notification((notification) => {
        console.log(notification.type);
    });

SMS Notifications (Vonage)

bash
composer require laravel/vonage-notification-channel guzzlehttp/guzzle
php
public function toVonage(object $notifiable): VonageMessage
{
    return (new VonageMessage)
        ->content('Hóa đơn #' . $this->invoice->id . ' đã thanh toán!');
}

Slack Notifications

bash
composer require laravel/slack-notification-channel
php
public function toSlack(object $notifiable): SlackMessage
{
    return (new SlackMessage)
        ->text('Hóa đơn #' . $this->invoice->id . ' đã thanh toán!')
        ->headerBlock('Thông báo hóa đơn')
        ->sectionBlock(function (SectionBlock $block) {
            $block->text('Hóa đơn đã được xử lý thành công.');
        });
}

Testing

php
use Illuminate\Support\Facades\Notification;

Notification::fake();

// Action...

Notification::assertSentTo(
    [$user], InvoicePaid::class
);

Notification::assertSentTo(
    $user,
    InvoicePaid::class,
    function (InvoicePaid $notification, array $channels) {
        return in_array('mail', $channels);
    }
);

Notification::assertNotSentTo([$user], AnotherNotification::class);
Notification::assertNothingSent();
Notification::assertCount(1);