# 消息通知
- [簡介](#introduction)
- [創建通知](#creating-notifications)
- [發送通知](#sending-notifications)
- [使用 Notifiable Trait](#using-the-notifiable-trait)
- [使用 Notification Facade](#using-the-notification-facade)
- [指定發送頻道](#specifying-delivery-channels)
- [通知隊列化](#queueing-notifications)
- [按需通知](#on-demand-notifications)
- [郵件通知](#mail-notifications)
- [格式化郵件信息](#formatting-mail-messages)
- [自定義接收者](#customizing-the-recipient)
- [自定義主題](#customizing-the-subject)
- [自定義模板](#customizing-the-templates)
- [Markdown 郵件通知](#markdown-mail-notifications)
- [生成消息](#generating-the-message)
- [寫消息](#writing-the-message)
- [自定義組件](#customizing-the-components)
- [數據庫通知](#database-notifications)
- [先決條件](#database-prerequisites)
- [格式化數據庫通知](#formatting-database-notifications)
- [訪問通知](#accessing-the-notifications)
- [標記已讀通知](#marking-notifications-as-read)
- [廣播通知](#broadcast-notifications)
- [先決條件](#broadcast-prerequisites)
- [格式化廣播系統](#formatting-broadcast-notifications)
- [監聽通知](#listening-for-notifications)
- [短信通知](#sms-notifications)
- [先決條件](#sms-prerequisites)
- [格式化短信通知](#formatting-sms-notifications)
- [自定義 "From" 電話號碼](#customizing-the-from-number)
- [短信通知路由](#routing-sms-notifications)
- [Slack 通知](#slack-notifications)
- [先決條件](#slack-prerequisites)
- [格式化 Slack 通知](#formatting-slack-notifications)
- [Slack 附件](#slack-attachments)
- [Slack 通知路由](#routing-slack-notifications)
- [本地化通知](#localizing-notifications)
- [通知事件](#notification-events)
- [自定義頻道](#custom-channels)
<a name="introduction"></a>
## 簡介
除了支持 [發送郵件](/docs/{{version}}/mail)之外,Laravel 還支持通過多種頻道發送通知,包括郵件、短信 (通過 [Nexmo](https://www.nexmo.com/)),以及 [Slack](https://slack.com)。通知還能存儲到數據庫以便后續在 Web 頁面中顯示。
通常,通知都是簡短、有信息量的消息,用于通知用戶應用中發生了什么。舉例來說,如果你是在編寫一個在線交易的應用,你應該會通過郵件和短信頻道類給用戶發送一條 「賬單支付」 的通知。
<a name="creating-notifications"></a>
## 創建通知
Laravel 中一條通知就是一個類 (通常存放在 `app/Notifications` 文件夾下)。看不到的話不要擔心,運行下 `make:notification` 命令就能創建了:
php artisan make:notification InvoicePaid
這條命令會在 `app/Notifications` 目錄下生成一個新的通知類。這個類包含 `via` 方法以及一個或多個消息構建的方法 (比如 `toMail` 或者 `toDatabase`) ,它們會針對指定的渠道把通知轉換為對應的消息。
<a name="sending-notifications"></a>
## 發送通知
<a name="using-the-notifiable-trait"></a>
### 使用 Notifiable Trait
通知可以通過兩種方法發送:`Notifiable` trait 的 `notify` 方法或 `Notification` [facade](/docs/{{version}}/facades)。首先讓我們來探討下使用 trait:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
}
默認的 `App\User` 模型中使用了這個 trait,它包含著一個可以用來發送通知的方法: `notify`。 `notify` 方法需要一個通知實例做參數:
use App\Notifications\InvoicePaid;
$user->notify(new InvoicePaid($invoice));
> {tip} 記住,你可以在任意模型中使用 `Illuminate\Notifications\Notifiable` trait,而不僅僅是在 `User` 模型中。
<a name="using-the-notification-facade"></a>
### 使用 Notification Facade
另外,你可以通過 `Notification` [facade](/docs/{{version}}/facades) 來發送通知。它主要用在當你給多個可接收通知的實體發送的時候,比如給用戶集合發送通知。使用 Facade 發送通知的話,要把可以接收通知和通知的實例傳遞給 `send` 方法:
Notification::send($users, new InvoicePaid($invoice));
<a name="specifying-delivery-channels"></a>
### 發送指定頻道
每個通知類都會有個 `via` 方法,它決定了通知會在哪個頻道上發送。開箱即用的頻道有 `mail`,`database`,`broadcast`,`nexmo` 和 `slack`。
> {tip} 如果你想使用其他的頻道,比如 Telegram 或者 Pusher,你可以去看下社區驅動的 [Laravel 通知頻道網站](http://laravel-notification-channels.com)。
`via` 方法接收一個 `$notifiable` 實例。這個實例將是通知實際發送到的類的實例。你可以用 `$notifiable` 來決定通知用哪些頻道來發送:
/**
* 獲取通知發送頻道。
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return $notifiable->prefers_sms ? ['nexmo'] : ['mail', 'database'];
}
<a name="queueing-notifications"></a>
### 通知隊列
> {注:} 使用通知隊列前需要配置隊列并 [開啟一個隊列任務](/docs/{{version}}/queues)。
發送通知可能是耗時的,尤其是通道需要調用額外的 API 來傳輸通知。為了加速應用的響應時間,可以將通知推送到隊列中異步發送,而要實現推送通知到隊列,可以讓對應通知類實現 `ShouldQueue` 接口并使用 `Queueable` trait 。 如果通知類是通過 `make:notification` 命令生成的,那么該接口和 trait 已經默認導入,你可以快速將它們添加到通知類:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
class InvoicePaid extends Notification implements ShouldQueue
{
use Queueable;
// ...
}
`ShouldQueue` 接口被添加到通知類以后,你可以像之前一樣正常發送通知,Laravel 會自動檢測到 `ShouldQueue` 接口然后將通知推送到隊列:
$user->notify(new InvoicePaid($invoice));
如果你想要延遲通知的發送,可以在通知實例后加上 `delay` 方法:
$when = now()->addMinutes(10);
$user->notify((new InvoicePaid($invoice))->delay($when);
<a name="on-demand-notifications"></a>
### 按需通知
有時候你可能需要發送通知給某個用戶,但是該用戶不存在于應用的用戶系統中,要實現這一目的,我們使用 `Notification::route` 方法在發送通知之前指定特別的通知路由:
Notification::route('mail', 'taylor@example.com')
->route('nexmo', '5555555555')
->notify(new InvoicePaid($invoice));
<a name="mail-notifications"></a>
## 郵件通知
<a name="formatting-mail-messages"></a>
### 格式化郵件消息
如果通知支持以郵件方式發送,你需要在通知類上定義一個 `toMail` 方法。該方法會接收一個 `$notifiable` 實體并返回 `Illuminate\Notifications\Messages\MailMessage` 實例。郵件消息可以包含多行文本以及對動作的調用,讓我們來看一個 `toMail` 方法的示例:
/**
* 獲取通知對應的郵件。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->greeting('Hello!')
->line('One of your invoices has been paid!')
->action('View Invoice', $url)
->line('Thank you for using our application!');
}
> {注:} 注意到我們在 `toMail` 方法中使用了 `$this->invoice->id` ,你可以傳遞任何通知生成消息所需要的數據到通知的構造器。
在這個例子中,我們注冊了一條問候、一行文本、對動作的調用以及另一行文本。 `MailMessage` 對象提供的這些方法讓格式化短小的事務郵件變得簡單快捷。`mail` 通道會將消息組件轉化為美觀的、響應式的、帶有純文本副本的 HTML 郵件模板。下面是一個通過 `mail` 通道生成的郵件示例:
<img src="https://laravel.com/assets/img/notification-example.png" width="551" height="596">
> {注:} 發送郵件通知時,確保在配置文件 `config/app.php` 中設置了 `name` 的值,該值將會用在郵件通知消息的頭部和尾部。
#### 其他通知格式化選項
除了在通知類中定義多行文本之外,你還可以使用 `view` 方法來指定一個自定義的、用于渲染通知郵件的模板:
/**
* 獲取通知郵件。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)->view(
'emails.name', ['invoice' => $this->invoice]
);
}
此外,你可以從 `toMail` 方法中返回一個 [可郵寄對象](/docs/{{version}}/mail) :
use App\Mail\InvoicePaid as Mailable;
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return Mailable
*/
public function toMail($notifiable)
{
return (new Mailable($this->invoice))->to($this->user->email);
}
<a name="error-messages"></a>
#### 錯誤消息
一些通知會告知用戶錯誤信息,例如失敗的訂單支付。你可以在構建消息的時候調用 `error` 方法來指示該郵件消息表示錯誤信息。在郵件消息中使用 `error` 方法時,動作按鈕將會變成紅色:
/**
* 獲取通知郵件。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Message
*/
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Notification Subject')
->line('...');
}
<a name="customizing-the-recipient"></a>
### 自定義接收人
通過 `mail` 通道發送通知時,通知系統會自動在被通知實體上查找 `email` 屬性,你可以通過在該實體上定義一個 `routeNotificationForMail` 來自定義使用哪個郵箱地址發送通知:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* 郵件通道通知的路由。
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForMail($notification)
{
return $this->email_address;
}
}
<a name="customizing-the-subject"></a>
### 自定義主題
默認情況下,郵件的主題就是格式為 「標題風格」 的通知類名,因此,如果通知類被命名為 `InvoicePaid`,郵件的主題就是 `Invoice Paid`,如果你想要為消息指定明確的主題,可以在構建消息的時候調用 `subject` 方法:
/**
* 獲取通知的郵件表示。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Notification Subject')
->line('...');
}
<a name="customizing-the-templates"></a>
### 自定義模板
你可以通過發布通知擴展包的資源來修改郵件通知所使用的 HTML 和純文本模板。運行完下面這個命令之后,郵件通知模板將會存放到 `resources/views/vendor/notifications` 目錄:
php artisan vendor:publish --tag=laravel-notifications
<a name="markdown-mail-notifications"></a>
## Markdown 郵件通知
Markdown 郵件通知允許你利用郵件通知的預置模板,從而讓你可以自由編寫更長、更具個性化的消息。因為這些消息以 Markdown 格式編寫,Laravel 還可以為它們渲染出高顏值、響應式的 HTML 模板,同時自動生成純文本的副本。
<a name="generating-the-message"></a>
### 生成消息
要生成帶有相應 Markdown 模板的通知,可以在使用 Artisan 命令 `make:notification` 時帶上 `--markdown` 選項:
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
和其他郵件通知一樣,使用 Markdown 模板的通知類也要定義一個 `toMail` 方法。不過,你可以使用 `markdown` 方法取代構造通知的 `line` 和 `action` 方法來指定要使用的 Markdown 模板名稱:
/**
* 獲取通知的郵件表示。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->subject('Invoice Paid')
->markdown('mail.invoice.paid', ['url' => $url]);
}
<a name="writing-the-message"></a>
### 編寫消息
Markdown 郵件通知聯合使用了 Blade 組件和 Markdown 語法,從而讓你在不脫離 Laravel 預置組件的情況下輕松構建通知:
@component('mail::message')
# Invoice Paid
Your invoice has been paid!
@component('mail::button', ['url' => $url])
View Invoice
@endcomponent
Thanks,<br>
{{ config('app.name') }}
@endcomponent
#### 按鈕組件
按鈕組件渲染一個居中的按鈕鏈接。該組件接收兩個參數, `url` 和可選的 `color`,支持的顏色有 `blue`, `green` 和 `red`。你可以添加任意數量的按鈕組件到消息中:
@component('mail::button', ['url' => $url, 'color' => 'green'])
View Invoice
@endcomponent
#### 面板組件
面板組件將給定的文字區塊渲染到一個面板中,并且有一個淡淡的背景色與周圍的消息區分開。適用于需要引起注意的文字區塊:
@component('mail::panel')
This is the panel content.
@endcomponent
#### 表格組件
表格組件允許你將一個 Markdown 表格轉化為 HTML 表格。該組件接收 Markdown 表格作為其內容。表格列對齊支持使用默認的 Markdown 表格列對齊語法:
@component('mail::table')
| Laravel | Table | Example |
| ------------- |:-------------:| --------:|
| Col 2 is | Centered | $10 |
| Col 3 is | Right-Aligned | $20 |
@endcomponent
<a name="customizing-the-components"></a>
### 自定義組件
你可以導出所有 Markdown 通知組件到應用中進行自定義,要導出組件,使用 Artisan 命令 `vendor:publish` 來發布 `laravel-mail` 資源標簽:
php artisan vendor:publish --tag=laravel-mail
該命令會發布 Markdown 郵件通知組件到 `resources/views/vendor/mail` 目錄。 `mail` 目錄包含 `html` 和 `markdown` 目錄,每個子目錄中又包含各自的所有有效組件。你可以按照自己的喜好自由編輯這些組件。
#### 自定義CSS
導出組件之后, `resources/views/vendor/mail/html/themes` 目錄將會包含一個默認的 `default.css` 文件,你可以在這個文件中自定義 CSS,這樣 Markdown 通知的 HTML 樣式就會自動調整。
> {注:} 如果你想要為 Markdown 組件構建全新的主題,只需在 `html/themes` 目錄中編寫一個新的 CSS 文件并修改 `mail` 配置文件的 `theme` 選項即可。
<a name="database-notifications"></a>
## 數據庫通知
<a name="database-prerequisites"></a>
### 預備知識
`database` 通知通道會在數據表中存儲通知信息,該表包含諸如通知類型以及用于描述通知的自定義 JSON 數據之類的信息。
你可以在用戶界面中查詢這個數據表來展示通知,不過,在此之前,需要創建數據表來保存信息,你可以使用 `notifications:table` 命令來生成遷移文件然后以此生成相應數據表:
php artisan notifications:table
php artisan migrate
<a name="formatting-database-notifications"></a>
### 格式化數據庫通知
如果通知支持存入數據庫表,就為通知類需要定義 `toDatabase` 或 `toArray` 方法。此方法接受 `$notifiable` 實體作參數并返回原生 PHP 數組。返回的數據將被編碼為 JSON 并存儲到 `notifications` 表的 `data` 列。來看一個 `toArray` 方法示例:
/**
* 獲取通知的數組表示。
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}
#### `toDatabase` Vs. `toArray`
`toArray` 方法還可以使用 `broadcast` 通道來判斷哪些數據被廣播到 JavaScript 客戶端。如果針對 `database` 和 `broadcast` 通道分別有兩個不同的數組表示,你需要定義 `toDatabase` 方法代替 `toArray` 方法。
<a name="accessing-the-notifications"></a>
### 訪問通知
一旦通知存入數據庫,就需要適當的方法自通知實體訪問它們。 包含在 Lareval 的默認 `App\User` 模型帶有 `Illuminate\Notifications\Notifiable` trait,它的`notifications` Eloquent 關聯方法能返回實體通知。要獲取通知,可以像其它 Eloquent 關聯方法一樣訪問此方法。默認情況下,通知按照 `created_at` 時間戳排序:
$user = App\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}
若要只獲取 「未讀」通知,可以使用 `unreadNotifications` 關聯方法。同樣這些通知按照 `created_at` 時間戳排序:
$user = App\User::find(1);
foreach ($user->unreadNotifications as $notification) {
echo $notification->type;
}
> {tip} 若要從 JavaScript 客戶端訪問通知,需要為應用定義一個通知控制器,它返回可通知實體的通知,比如當前用戶。可以從 JavaScript 客戶端向該控制器 URI 發送 HTTP 請求。
<a name="marking-notifications-as-read"></a>
### 標記通知已讀
通常,在用戶閱覽一條通知之后,你會想將其標識為「已讀」。 `Illuminate\Notifications\Notifiable` trait 提供了 `markAsRead` 方法,它更新數據庫中通知記錄的 `read_at` 列:
$user = App\User::find(1);
foreach ($user->unreadNotifications as $notification) {
$notification->markAsRead();
}
可以在通知控制集合上直接使用 `markAsRead` 方法代替循環調用通知:
$user->unreadNotifications->markAsRead();
還可以使用指更新將所有的通知標為已讀,而不從數據庫中讀取它們:
$user = App\User::find(1);
$user->unreadNotifications()->update(['read_at' => now()]);
可以使用 `delete` 方法從表中整個刪除通知:
$user->notifications()->delete();
<a name="broadcast-notifications"></a>
## 廣播通知
<a name="broadcast-prerequisites"></a>
### 預備知識
廣播通知前,你需要配置和熟悉 Laravel 的 [事件廣播](/docs/{{version}}/broadcasting) 服務。事件廣播提供了在 JavaScript 客戶端響應服務端觸發 Laravel 事件的方法。
<a name="formatting-broadcast-notifications"></a>
### 格式化廣播通知
`broadcast` 通道使用 Laravel 的 [event broadcasting](/docs/{{version}}/broadcasting) 服務廣播通知,它允許 JavaScript客戶端實時捕獲通知。如果通知支持廣播,你就需要在通知類上定義 `toBroadcast` 方法。此方法接受 `$notifiable` 實體作為參數,并返回 `BroadcastMessage` 實例。返回的數據將被編碼為 JSON 并廣播給 JavaScript 客戶端。我們來看一個 `toBroadcast` 方法示例
use Illuminate\Notifications\Messages\BroadcastMessage;
/**
* 獲取通知的可廣播表示。
*
* @param mixed $notifiable
* @return BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
]);
}
#### 廣播隊列配置
所有的廣播通知都被放入廣播隊列。想要配置用于廣播操作的隊列連接或者隊列名稱,需要使用 `BroadcastMessage` 的 `onConnection` 和 `onQueue` 方法:
return (new BroadcastMessage($data))
->onConnection('sqs')
->onQueue('broadcasts');
> {tip} 除了指定的數據,廣播通知還包含 `type` 域,它包括通知類的類名。
<a name="listening-for-notifications"></a>
### 監聽通知
通知將會以格式化為 `{notifiable}.{id}` 的形式在私有頻道上廣播,因此,如果你要發送通知到 ID 為 `1` 的 `App\User` 實例,那么該通知將會在私有頻道 `App.User.1` 上進行廣播,如果使用了 [Laravel Echo](/docs/{{version}}/broadcasting),可以使用輔助函數 `notification` 輕松在某個頻道上監聽通知:
Echo.private('App.User.' + userId)
.notification((notification) => {
console.log(notification.type);
});
#### 自定義通知通道
如果你想要自定義被通知實體在某個通道上接收廣播通知,可以在被通知實體上定義一個 `receivesBroadcastNotificationsOn` 方法:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* 用戶接收廣播通知的通道。
*
* @return string
*/
public function receivesBroadcastNotificationsOn()
{
return 'users.'.$this->id;
}
}
<a name="sms-notifications"></a>
## 短信(SMS)通知
<a name="sms-prerequisites"></a>
### 預備知識
Laravel 基于 [Nexmo](https://www.nexmo.com/) 發送短信通知,在使用Nexmo 發送通知前,需要安裝對應 Composer 依賴包 `laravel/nexmo-notification-channel` :
composer require laravel/nexmo-notification-channel
下一步,你需要在配置文件 `config/services.php` 中進行相應配置。你可以參考以下示例配置:
'nexmo' => [
'key' => env('NEXMO_KEY'),
'secret' => env('NEXMO_SECRET'),
'sms_from' => '15556666666',
],
`sms_from` 配置項就是你用于發送短信消息的手機號碼,你需要在 Nexmo 控制面板中為應用生成一個手機號碼。
<a name="formatting-sms-notifications"></a>
### 格式化短信通知
如果通知支持以短信方式發送,那么你需要在通知類上定義一個 `toNexmo` 方法。該方法接收一個 `$notifiable` 實體并返回 `Illuminate\Notifications\Messages\NexmoMessage` 實例:
/**
* Get the Nexmo / SMS representation of the notification.
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your SMS message content');
}
#### Unicode 內容
如果你的短信消息包含 Unicode 字符,需要在構造 `NexmoMessage` 實例時調用 `unicode` 方法:
/**
* Get the Nexmo / SMS representation of the notification.
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your unicode message')
->unicode();
}
<a name="customizing-the-from-number"></a>
### 自定義 "發送" 號碼
如果你要通過與配置文件 `config/services.php` 中指定的手機號不同的其他號碼發送通知,可以使用 `NexmoMessage` 實例上的 `from` 方法:
/**
* Get the Nexmo / SMS representation of the notification.
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your SMS message content')
->from('15554443333');
}
<a name="routing-sms-notifications"></a>
### 短信通知路由
使用 `nexmo` 通道發送通知的時候,通知系統會自動在被通知實體上查找 `phone_number` 屬性。如果你想要自定義通知被發送到的手機號碼,可以在該實體上定義一個 `routeNotificationForNexmo` 方法:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* Route notifications for the Nexmo channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForNexmo($notification)
{
return $this->phone;
}
}
<a name="slack-notifications"></a>
## Slack 通知
<a name="slack-prerequisites"></a>
### 預備知識
在通過 Slack 發送通知前,必須通過 Composer 安裝 Slack 通知通道:
composer require laravel/slack-notification-channel
此外,你還要為 Slack 組配置一個 ["Incoming Webhook"](https://api.slack.com/incoming-webhooks) 集成。該集成會在你進行 [Slack 通知路由](#routing-slack-notifications) 的時候提供一個URL。
<a name="formatting-slack-notifications"></a>
### 格式化 Slack 通知
如果通知支持通過 Slack 消息發送,則需要在通知類上定義一個 `toSlack` 方法,該方法接收一個 `$notifiable` 實體并返回 `Illuminate\Notifications\Messages\SlackMessage` 實例,該實例包含文本內容以及格式化額外文本或數組字段的“附件”。讓我們來看一個基本的 `toSlack` 使用示例:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('One of your invoices has been paid!');
}
在這個例子中,我們只發送一行簡單的文本到 Slack,最終創建的消息如下:
<img src="https://laravel.com/assets/img/basic-slack-notification.png">
#### Customizing The Sender & Recipient
你可以使用 `from` 和 `to` 方法自定義發送者和接收者, `from` 方法接收一個用戶名和 emoji 標識,而 `to` 方法接收通道或用戶名:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('Ghost', ':ghost:')
->to('#other')
->content('This will be sent to #other');
}
還可以使用圖片作為 logo 用以取代 emoji:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('Laravel')
->image('https://laravel.com/favicon.png')
->content('This will display the Laravel logo next to the message');
}
<a name="slack-attachments"></a>
### Slack 附件
你還可以添加“附件”到 Slack 消息。相對簡單文本消息,附件可以提供更加豐富的格式選擇。在這個例子中,我們會發送一個在應用程序中出現的異常錯誤通知,包含查看更多異常細節的鏈接:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
$url = url('/exceptions/'.$this->exception->id);
return (new SlackMessage)
->error()
->content('Whoops! Something went wrong.')
->attachment(function ($attachment) use ($url) {
$attachment->title('Exception: File Not Found', $url)
->content('File [background.jpg] was not found.');
});
}
上述代碼會生成如下 Slack 消息:
<img src="https://laravel.com/assets/img/basic-slack-attachment.png">
附件還允許你指定要呈獻給用戶的數組數據。為了提高可讀性,給定的數組會以表格形式展示:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
$url = url('/invoices/'.$this->invoice->id);
return (new SlackMessage)
->success()
->content('One of your invoices has been paid!')
->attachment(function ($attachment) use ($url) {
$attachment->title('Invoice 1322', $url)
->fields([
'Title' => 'Server Expenses',
'Amount' => '$1,234',
'Via' => 'American Express',
'Was Overdue' => ':-1:',
]);
});
}
上述代碼會生成如下 Slack 消息:
<img src="https://laravel.com/assets/img/slack-fields-attachment.png">
#### Markdown 附件內容
如果一些附件字段包含 Markdown,可以使用 `markdown` 方法來構建 Slack 用以解析并顯示以 Markdown 格式編寫的附件字段,該方法支持的值包括 `pretext`、 `text` 或 `fields`。想要了解更多關于 Slack 格式化的信息,查看 [Slack API 文檔](https://api.slack.com/docs/message-formatting#message_formatting):
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
$url = url('/exceptions/'.$this->exception->id);
return (new SlackMessage)
->error()
->content('Whoops! Something went wrong.')
->attachment(function ($attachment) use ($url) {
$attachment->title('Exception: File Not Found', $url)
->content('File [background.jpg] was *not found*.')
->markdown(['text']);
});
}
<a name="routing-slack-notifications"></a>
### Slack 通知路由
要路由 Slack 通知到適當的位置,需要在被通知的實體上定義一個 `routeNotificationForSlack` 方法,這將會返回通知被發送到的 Webhook URL。Webhook URL 可通過在 Slack 組上添加一個 "Incoming Webhook" 服務來生成:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* Route notifications for the Slack channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForSlack($notification)
{
return 'https://hooks.slack.com/services/...';
}
}
<a name="localizing-notifications"></a>
## 本地化通知
Laravel 允許您以當前語言環境之外的其他語言發送通知,并且會在通知隊列時記住該語言環境。
要實現這一點, `Illuminate\Notifications\Notification` 類提供了一個 `locale` 方法來設置所需的語言。在格式化通知時,應用程序將更改為此語言設置,然后在格式化完成后還原為以前的語言設置:
$user->notify((new InvoicePaid($invoice))->locale('es'));
多重通知的本地化也可通過 `Notification` Facade 實現:
Notification::locale('es')->send($users, new InvoicePaid($invoice));
### 用戶首選語言區域設置
有些情況下,應用程序保存了每個用戶的首選語言區域設置。通過在模型上實現 `HasLocalePreference` 契約,可以指定 Laravel 在發送通知時使用用戶保存的首選語言設置:
use Illuminate\Contracts\Translation\HasLocalePreference;
class User extends Model implements HasLocalePreference
{
/**
* Get the user's preferred locale.
*
* @return string
*/
public function preferredLocale()
{
return $this->locale;
}
}
實現接口后,Laravel 將在向模型發送通知和郵件時自動使用首選區域設置。因此,使用此接口時不需要調用 `locale` 方法:
$user->notify(new InvoicePaid($invoice));
<a name="notification-events"></a>
## 通知事件
當通知被發送后,通知系統會觸發 `Illuminate\Notifications\Events\NotificationSent` 事件,該事件實例包含被通知的實體(如用戶)和通知實例本身。你可以在 `EventServiceProvider` 中為該事件注冊監聽器:
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Illuminate\Notifications\Events\NotificationSent' => [
'App\Listeners\LogNotification',
],
];
> {提示} 在 `EventServiceProvider` 中注冊監聽器之后,使用 Artisan 命令 `event:generate` 可以快速生成監聽器類。
在事件監聽器中,可以訪問事件的 `notifiable`、 `notification` 和 `channel` 屬性了解通知接收者和通知本身的更多信息:
/**
* Handle the event.
*
* @param NotificationSent $event
* @return void
*/
public function handle(NotificationSent $event)
{
// $event->channel
// $event->notifiable
// $event->notification
// $event->response
}
<a name="custom-channels"></a>
## 自定義通道
Laravel 為我們提供了多種通知通道,但是嘗試編寫自定義通道驅動以通過其他通道發送通知,也很簡單。首先定義一個包含 `send` 方法的類,該方法接收兩個參數: `$notifiable` 和 `$notification`:
<?php
namespace App\Channels;
use Illuminate\Notifications\Notification;
class VoiceChannel
{
/**
* 發送指定的通知.
*
* @param mixed $notifiable
* @param \Illuminate\Notifications\Notification $notification
* @return void
*/
public function send($notifiable, Notification $notification)
{
$message = $notification->toVoice($notifiable);
// Send notification to the $notifiable instance...
}
}
一旦通知通道類被定義后,就可以在應用中通過 `via` 方法返回類名:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use App\Channels\VoiceChannel;
use App\Channels\Messages\VoiceMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
class InvoicePaid extends Notification
{
use Queueable;
/**
* 獲取通知通道.
*
* @param mixed $notifiable
* @return array|string
*/
public function via($notifiable)
{
return [VoiceChannel::class];
}
/**
* 獲取語音表示的通知.
*
* @param mixed $notifiable
* @return VoiceMessage
*/
public function toVoice($notifiable)
{
// ...
}
}
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View