* * * * *
[TOC]
## 簡介
除了?[發送郵件](http://www.hmoore.net/tonyyu/laravel_5_6/786245)?Laravel 還支持通過多種頻道發送通知,包括郵件、短信 (通過?[Nexmo](https://www.nexmo.com/)), 以及?[Slack](https://slack.com/)。通知還能存到數據庫,這樣就能在網頁界面上顯示了。
通常情況下,通知應該是簡短、有信息量的消息來通知用戶你的應用發生了什么。舉例來說,如果你在編寫一個在線交易應用,你應該會通過郵件和短信頻道來給用戶發送一條 「賬單已付」 的通知。
## 創建通知
Laravel 中一條通知就是一個類(通常存在?`app/Notifications`?文件夾里)。看不到的話不要擔心,運行一下?`make:notification`?命令就能創建了:
~~~
php artisan make:notification InvoicePaid
~~~
這個命令會在?`app/Notifications`?目錄下生成一個新的通知類。這個類包含?`via`?方法和幾個消息構建方法(比如?`toMail`?或?`toDatabase`),它們會針對指定的渠道把通知轉換過為對應的消息。
## 發送通知
### 使用 Notifiable Trait
通知可以通過兩種方法發送:?`Notifiable`?trait 的`notify`?方法或?`Notification`?[facade](http://www.hmoore.net/tonyyu/laravel_5_6/786058)。首先,讓我們探索使用 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`?模型中。
### 使用 Notification Facade
另外,你可以通過?`Notification`?[facade](http://www.hmoore.net/tonyyu/laravel_5_6/786058)?來發送通知。它主要用在當你給多個可接收通知的實體發送通知的時候,比如給用戶集合發通知。要用 facade 發送通知的話,要把可接收通知的實體和通知的實例傳遞給?`send`?方法:
~~~
Notification::send($users, new InvoicePaid($invoice));
~~~
### 指定發送頻道
每個通知類都有個?`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'];
}
~~~
### 隊列化通知
> {note} 在隊列化通知之前你應該配置你的隊列并且?[啟動隊列處理器](http://www.hmoore.net/tonyyu/laravel_5_6/786248).
發送通知可能很耗時,尤其是是當頻道需要一個額外的 API 來發送通知。要加速你的應用響應時間,讓你的通知繼承?`ShouldQueue`?接口 并且在你的類中添加?`Queueable`?trait。這些接口和 trait 已經被使用?`make:notification`?生成的所有通知引入了,所以你可以直接將他們添加到你的通知類:
~~~
<?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));
~~~
### 按需通知
有時你可能需要發送通知給一個非應用中的用戶。使用?`Notification::route`?方法,你在發送通知之前可以指定點對點的通知信息:
~~~
Notification::route('mail', 'taylor@laravel.com')
->route('nexmo', '5555555555')
->notify(new InvoicePaid($invoice));
~~~
## 郵件通知
### 格式化郵件信息
如果一個通知支持郵件發送,你應該定義一個?`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!');
}
~~~
> {tip} 注意我們在?`toMail`?方法中使用了?`$this->invoice->id`?。你可以在通知生成它的消息時傳遞給通知的構造函數任意數據。
在這個例子里,我們注冊了一個問候,一行文本,一個鏈接和另一行文本。這些方法由?`MailMessage`?對象提供,這使格式化簡單的事務性的郵件變得簡單。然后,郵件頻道將把文本轉換成一個帶有文字的漂亮的響應式 HTML 郵件模板。這是一個由「郵件」頻道生成的 email 的樣例:
[](https://laravel.com/assets/img/notification-example.png)
[](https://laravel.com/assets/img/notification-example.png)
> {tip} 在發送郵件通知時,請確定在你的?`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 方法中返回一個?[mailable](http://www.hmoore.net/tonyyu/laravel_5_6/786245)?對象。
~~~
use App\Mail\InvoicePaid as Mailable;
/**
* 獲取通知的郵件展示方式。
*
* @param mixed $notifiable
* @return Mailable
*/
public function toMail($notifiable)
{
return (new Mailable($this->invoice))->to($this->user->email);
}
~~~
#### 錯誤消息
有些通知是給用戶提示錯誤,比如賬單支付失敗的提示。你可以通過調用?`error`?方法來指定這條郵件消息被當做一個錯誤提示。當郵件消息使用了?`error`?方法后,引導鏈接按鈕會變成紅色而非藍色:
~~~
/**
* 獲取通知的郵件展示方式。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Message
*/
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Notification Subject')
->line('...');
}
~~~
### 自定義接收者
當通過?`mail`?頻道來發送通知的時候,通知系統將會自動尋找你的 notifiable 實體中的?`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;
}
}
~~~
### 自定義主題
默認情況下,郵件主題是格式化成了標題格式的通知類的類名。所以如果你對通知類名為?`InvoicePaid`?,郵件主題將會是?`Invoice Paid`?。如果你想顯式指定消息的主題,你可以在構建消息時調用?`subject`?方法:
~~~
/**
*獲取通知的郵件展示方式。
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Notification Subject')
->line('...');
}
~~~
### 自定義模板
你可以通過發布通知包的資源來修改 HTML 模板和純文本模板。運行這個命令后,郵件通知模板就被放在了?`resources/views/vendor/notifications`?文件夾下:
~~~
php artisan vendor:publish --tag=laravel-notifications
~~~
## Markdown 郵件通知
Markdown 郵件通知可讓您利用郵件通知的預先構建的模板,同時給予您更多自由地撰寫更長的自定義郵件。 由于消息是用 Markdown 編寫的, Laravel 能夠為消息呈現漂亮,響應的 HTML 模板,同時還自動生成純文本對應。
### 生成消息
要使用相應的 Markdown 模板生成通知,您可以使用?`make:notification`?Artisan命令的?`--markdown`?選項:
~~~
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
~~~
與所有其他郵件通知一樣,使用 Markdown 模板的通知應在其通知類上定義一個?`toMail`?方法。 但是,不使用?`line`?和?`action`?方法來構造通知,而是使用?`markdown`?方法來指定應該使用的 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]);
}
~~~
### 編寫消息
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
~~~
### 自定義組件
你可以將所有的 Markdown 通知組件導出到你的應用中,以進行自定義。要導出組件,請使用?`vendor:publish`?Artisan 命令來發布?`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 展示之中。
> {tip} 如果你喜歡為 Markdown 組件創建一整個新主題,只需要在?`html/themes`?目錄中編寫一個新的 CSS 文件,并修改?`mail`?配置文件中的?`theme`?選項。
## 數據庫通知
### 先決條件
`database`?通知渠道在一張數據庫表里存儲通知信息。該表以自定義的 JSON 格式,存儲如通知類型等描述通知的信息。
你可以為你的應用提供查詢這些表,以顯示通知的用戶接口。不過,在此之前,你需要先創建一個數據庫表來存放這些通知。你可以使用命令?`notifications:table`?生成包含特定表結構的遷移文件:
~~~
php artisan notifications:table
php artisan migrate
~~~
### 格式化數據庫通知
要讓一個通知支持被存儲到數據庫表中,你需要為通知類定義方法?`toDatabase`?或者?`toArray`。這個方法應當接受一個?`$notifiable`?的實體作為參數,并且可以返回一個普通的 PHP 數組。被返回的數組將被編碼為 JSON 并存儲在你的?`notifications`?表的?`data`?數據列。讓我們看一個?`toArray`?方法的例子:
~~~
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
];
}
~~~
#### 比較?`toDatabase`?和?`toArray`
`toArray`?方法也會被?`broadcast`?渠道用來判斷哪些數據會被廣播給你的 JavaScript 客戶端。如果你希望?`database`?和?`broacast`?兩個渠道有不同的數組展現方式,你需要定義?`toDatabase`?以取代定義?`toArray`?方法。
### 存取通知
一旦通知被存儲到數據庫之中,你需要一種方便的方式從通知實體中獲取它們。Laravel 的默認模型?`App\User`?已經引入了 Trait?`Illuminate\Notifications\Notifiable`?,它包含了一個 Eloquet 關系?`notifications`?,可以為實體返回通知。你可以像訪問所有其他 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 請求。
### 通知標記已讀
通常,你希望一個通知在用戶瀏覽之后就標記為「已讀」。Trait?`Illuminate\Notifications\Notifiable`?提供一個?`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();
~~~
## 廣播通知
### 先決條件
在廣播通知之前,你需要配置并熟悉 Laravel 的?[事件廣播](http://www.hmoore.net/tonyyu/laravel_5_6/786239)?服務。事件廣播提供一種途徑,讓 JavaScript 客戶端可以響應服務端觸發的 Laravel 事件端。
### 格式化廣播通知
`broadcast`?渠道使用 Laravel 的?[事件廣播](http://www.hmoore.net/tonyyu/laravel_5_6/786239)?廣播通知,允許你的 JavaScript 客戶端實時抓取通知。你需要為通知類定義?`toBroadcast`?方法,以使該通知支持廣播。這個方法獲取一個?`$notifiable`?的實體,并需要返回一個?`BroadcastMessage`?實例。返回的數據會被編碼為 JSON,并且廣播給你的 JavaScript 客戶端。讓我們看一個?`toBroadcast`?方法的示例:
~~~
use Illuminate\Notifications\Messages\BroadcastMessage;
/**
* Get the broadcastable representation of the notification.
*
* @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`?字段,這個字段包含了通知類的類名。
### 監聽通知
通知將會在一個私有頻道里進行廣播,頻道格式為?`{notifiable}.{id}`?。所以,如果你給 ID 為?`1`?的?`App\User`示例發送通知,這個通知就在?`App.User.1`?私有通道里被發送。當你使用?[Laravel Echo](http://www.hmoore.net/tonyyu/laravel_5_6/786239)?的時候,你可以很簡單的使用?`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;
}
}
~~~
## 短信通知
### 實現前提
Laravel 的短信通知基于?[Nexmo](https://www.nexmo.com/)。使用 Nexmo 發送通知前,需要安裝?`nexmo/client`?的 Composer 包并且配置好?`config/services.php`?文件。可以直接復制以下配置示例:
~~~
'nexmo' => [
'key' => env('NEXMO_KEY'),
'secret' => env('NEXMO_SECRET'),
'sms_from' => '15556666666',
],
~~~
`sms_from`?選項代表短信發送者的號碼,可以在 Nexmo 控制面板里生成。
### 格式化短信通知
要實現短信通知,需要在通知類里定義?`toNexmo`?方法。這個方法接受一個?`$notifiable`?實例,必須返回`Illuminate\Notifications\Messages\NexmoMessage`?實例:
~~~
/**
* 獲取 Nexmo / 短信通知
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your SMS message content');
}
~~~
#### Unicode 內容
如果短信包含 unicode 字符,就應在?`NexmoMessage`?實例上調用?`unicode`?方法:
~~~
/**
* 獲取 Nexmo / 短信通知
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your unicode message')
->unicode();
}
~~~
### 自定義發送者號碼
`config/services.php`?中的發送者號碼與欲使用的發送者號碼不一致時,就可以使用?`NexmoMessage`?實例上的?`from`?方法:
~~~
/**
* 獲取 Nexmo / 短信通知
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable)
{
return (new NexmoMessage)
->content('Your SMS message content')
->from('15554443333');
}
~~~
### 路由短信通知
當通過?`mexmo`?渠道發送通知是,通知系統會自動在通知實體中尋找?`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;
}
}
~~~
## Slack 通知
### 先決條件
在你通過 Slack 發送通知之前,你必須通過 Composer 安裝 Guzzle HTTP 庫:
~~~
composer require guzzlehttp/guzzle
~~~
你需要為你的 Slack 組配置?["Incoming Webhook"](https://api.slack.com/incoming-webhooks)?集成,它將為你提供?[路由 Slack 通知](http://www.hmoore.net/tonyyu/laravel_5_6/786246#_Slack__810)?時所需要的 URL。
### 格式化 Slack 通知
要使一個通知支持被發送為一個 Slack 消息,你需要為通知類定義一個?`toSlack`?方法。該方法應接受一個?`$notifiable`?實體為參數,并可以返回一個?`Illuminate\Notifications\Messages\SlackMessage`?實例。 Slack 消息需要包含文本內容,以及一個「attachement」 用來附加額外的文本或者數組字段。讓我來看一個基本的?`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,它將創建類似如下的一個消息:
[](https://laravel.com/assets/img/basic-slack-notification.png)
[](https://laravel.com/assets/img/basic-slack-notification.png)
#### 自定義發送人和收件人
你可以使用?`from`?和?`to`?方法來自定義發送人和收件人。`form`?方法接受一個用戶名和 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');
}
~~~
你也可以使用圖片來代替 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');
}
~~~
### 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 消息:
[](https://laravel.com/assets/img/basic-slack-attachment.png)
[](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 消息:
[](https://laravel.com/assets/img/slack-fields-attachment.png)
[](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']);
});
}
~~~
### 路由 Slack 通知
要把 Slack 通知路由到正確的位置,需要為你的可通知實體定義一個?`routeNotificationForSlack`?方法。它返回通知將被發送到的 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 $this->slack_webhook_url;
}
}
~~~
## 通知事件
發送通知之后,通知系統就會觸發?`Illuminate\Notifications\Events\NotificationSent`?事件。它包含「notifiable」實體,和通知實例本身。你可以在?`EventServiceProvider`?中為該事件注冊監聽器:
~~~
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Illuminate\Notifications\Events\NotificationSent' => [
'App\Listeners\LogNotification',
],
];
~~~
> {tip} 別忘記在?`EventServiceProvider`?中注冊監聽器之后,使用?`event:generate`?Artisan 命令快速生成監聽器類。
在一個事件監聽器中,你可以訪問事件的?`notifiable`,`notification`,和?`channel`?屬性,來了解通知接受者和通知本身:
~~~
/**
* Handle the event.
*
* @param NotificationSent $event
* @return void
*/
public function handle(NotificationSent $event)
{
// $event->channel
// $event->notifiable
// $event->notification
}
~~~
## 自定義頻道
Laravel 附帶少數的通知頻道,但你可能需要編寫自己的驅動以便通過其它頻道發送通知。 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);
// 將通知發送到 $notifiable 實例...
}
}
~~~
一旦定義了通知頻道類,你可以從任何通知類的?`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)
{
// ...
}
}
~~~
- 前言
- 翻譯說明
- 發行說明
- 升級指南
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- Homestead
- Valet
- 部署
- 核心架構
- 請求周期
- 服務容器
- 服務提供者
- Facades
- Contracts
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 前端指南
- 編輯資源 Mix
- 安全相關
- 用戶認證
- Passport OAuth 認證
- 用戶授權
- 加密解密
- 哈希
- 重置密碼
- 綜合話題
- Artisan 命令行
- 廣播系統
- 緩存系統
- 集合
- 事件系統
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent 集合
- 修改器
- API 資源
- 序列化
- 測試相關
- 快速入門
- HTTP 測試
- 瀏覽器測試 Dusk
- 數據庫測試
- 測試模擬器
- 官方擴展包
- Cashier 交易工具包
- Envoy 部署工具
- Horizon
- Scout 全文搜索
- Socialite 社會化登錄