Laravel Notification 通知訊息

建立通知類別

通知類別預設放置於 app/Notifications 目錄。

php artisan make:notification InvoicePaid

建立資料庫通知資料表

若使用 database 頻道儲存通知,需先建立對應的資料表:

php artisan notifications:table
php artisan migrate

寄送通知方式

Laravel 提供兩種方式寄送通知:

1. 使用 Notifiable Trait

模型需使用 Illuminate\Notifications\Notifiable Trait(預設 User 模型已使用)。

use App\Notifications\InvoicePaid;

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

2. 使用 Notification Facade

可用於一次發送給多個可通知的實體。

use Illuminate\Support\Facades\Notification;
use App\Notifications\InvoicePaid;

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

指定通知的遞送頻道

在通知類別中,via 方法決定通知發送的頻道,可用選項包括:

  • mail
  • database
  • broadcast
  • slack
  • nexmo

範例:使用資料庫頻道儲存通知

public function via($notifiable)
{
    return ['database'];
}

自訂通知內容

使用 toArray() 方法定義儲存在資料庫中的內容:

public function toArray($notifiable)
{
    return [
        'message' => 'somethingText',
    ];
}

存取通知資料

取得所有通知:

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

foreach ($user->notifications as $notification) {
    echo $notification->data['message'];
}

取得未讀通知:

foreach ($user->unreadNotifications as $notification) {
    echo $notification->data['message'];
}

備註:

  • Laravel 的 notifications 關聯會自動透過 Illuminate\Notifications\DatabaseNotification 模型進行資料處理。
  • 使用 markAsRead()delete() 可標記為已讀或刪除通知。