教程 > laravel 教程 > 阅读:69

laravel 通知——迹忆客-ag捕鱼王app官网

简介

除了支持发送邮件之外,laravel 还支持通过多种传输通道发送通知,这些通道包括邮件、短信(通过 nexmo)以及 slack 等。通知可以存储在数据库以便后续在 web 界面中显示。

通常,通知都是很短的、用于告知用户应用中所发生事件的消息。例如,如果我们要开发一个计费应用,则需要通过邮件或短信等渠道给用户发送“账单支付”通知。


创建通知

在 laravel 中,每个通知都以单独类的形式存在(通常存放在 app/notifications 目录),如果在应用中没看到这个目录,别担心,它将会在运行 artisan 命令 make:notification 的时候自动创建:

$ php artisan make:notification invoicepaid

该命令会在 app/notifications 目录下生成一个新的通知类,每个通知类都包含一个 via 方法以及多个消息构建方法(如 tomailtodatabase),这些消息构建方法用于将通知转化成为特定渠道优化的消息。默认生成的模板代码如下:


发送通知

使用 notifiable trait

通知可以通过两种方式发送:使用 notifiable trait 提供的 notify 方法或者使用 notification 门面。首先,我们使用 notifiable trait 来测试:

trait 被默认的 app\user 模型使用并提供一个可用于发送通知的方法:notify。notify 方法接收一个通知实例:

use app\notifications\invoicepaid;
$user->notify(new invoicepaid($invoice));

注:我们可以在任何模型中使用 illuminate\notifications\notifiable trait,不限于只在 user 模型中使用。

使用 notification facade

作为替代方案,还可以通过 notification 门面发送通知。这在你需要发送通知给多个用户的时候很有用,要使用这个门面发送通知,需要将所有被通知用户和通知实例传递给 send 方法:

notification::send($users, new invoicepaid($invoice));

指定传输通道

每个通知类都有一个 via 方法用于决定通知通过何种通道传输,laravel 开箱支持 mail、 database、 broadcast、 nexmo 以及 slack 通道。

注:如果你想要使用其他传输通道,比如 telegram 或 pusher,参考社区提供的驱动:laravel通知通道网站。

via 方法接收一个 $notifiable 实例,用于指定通知被发送到的类实例。你可以使用 $notifiable 来判断通知通过何种通道传输:

/**
 * get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 * @translator laravelacademy.org
 */
public function via($notifiable)
{
    return $notifiable->prefers_sms ? ['nexmo'] : ['mail', 'database'];
}

通知队列

注意:使用通知队列前需要配置队列并开启一个队列任务。

发送通知可能是比较耗时间的,尤其是通道需要调用额外的 api 来传输通知。为了加速应用的响应时间,可以将通知推送到队列中异步发送,而要实现推送通知到队列,可以让对应通知类实现 shouldqueue 接口并使用 queueable trait。如果通知类是通过 make:notification 命令生成的,那么该接口和 trait 已经默认导入,你可以快速将它们添加到通知类:

shouldqueue 接口被添加到通知类以后,你可以像之前一样正常发送通知,laravel 会自动检测到 shouldqueue 接口然后将通知推送到队列:

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

如果我们想要延迟通知的发送,可以在通知实例后加上 delay 方法:

$when = carbon::now()->addminutes(10);
$user->notify((new invoicepaid($invoice))->delay($when));

自定义通知通道队列

如果我们想为通知支持的每个通知通道指定一个特定的队列,我们可以在通知类里定义一个viaqueues方法。这个方法应该返回一个通道名称/队列名称对的数组:

/**
 * determine which queues should be used for each notification channel.
 *
 * @return array
 */
public function viaqueues()
{
    return [
        'mail' => 'mail-queue',
        'slack' => 'slack-queue',
    ];
}

按需发送通知

有时候我们可能需要发送通知给某个用户,但是该用户不存在于应用的用户系统中,要实现这一目的,我们使用 notification::route 方法在发送同之前指定特别的通知路由:

notification::route('mail', 'taylor@laravel.com')
        ->route('nexmo', '5555555555')
        ->route('slack', 'https://hooks.slack.com/services/...')
        ->notify(new invoicepaid($invoice));

邮件通知

格式化邮件消息

如果通知支持以邮件方式发送,你需要在通知类上定义一个 tomail 方法。该方法会接收一个 $notifiable 实体并返回 illuminate\notifications\messages\mailmessage 实例。邮件消息可以包含多行文本以及对动作的调用,让我们来看一个 tomail 方法的示例:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    $url = ;
    return (new mailmessage)
        ->greeting('hello!')
        ->line('one of your invoices has been paid!')
        ->action('view invoice', $url)
        ->line('thank you for using our application!');
}

注:注意到我们在 message 方法中使用了 $this->invoice->id,你可以传递任何通知生成消息所需要的数据到通知的构造器。

在这个例子中,我们注册了一条问候、一行文本、对动作的调用以及另一行文本。mailmessage 对象提供的这些方法让格式化短小的事务邮件变得简单快捷。mail 通道会将消息组件转化为美观的、响应式的、带有纯文本副本的 html 邮件模板。下面是一个通过 mail 通道生成的邮件示例:

mail通道生成的邮件示例

注:发送邮件通知时,确保在配置文件 config/app.php 中设置了 name 的值,该值将会用在邮件通知消息的头部和尾部。

其他通知格式化选项

除了在通知类中定义多行文本之外,你还可以使用 view 方法来指定一个自定义的、用于渲染通知邮件的模板:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 * @translator laravelacademy.org
 */
public function tomail($notifiable)
{
    return (new mailmessage)->view(
        'emails.name', ['invoice' => $this->invoice]
    );
}

我们可以通过将视图名称作为数组的第二个元素传递给 mailmessage 的view方法来为邮件消息指定纯文本视图:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    return (new mailmessage)->view(
        ['emails.name.html', 'emails.name.plain'], 
        ['invoice' => $this->invoice]
    );
}

此外,我们可以从 tomail 方法中返回一个可邮寄对象:

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);
}

错误消息

一些通知会告知用户错误信息,例如失败的订单支付,我们可以在构建消息的时候调用 error 方法来指示该邮件消息表示错误信息。在邮件消息中使用 error 方法时,动作按钮将会变成红色:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\message
 */
public function tomail($notifiable)
{
    return (new mailmessage)
                ->error()
                ->subject('notification subject')
                ->line('...');
}

自定义发送人

默认情况下,邮件的发送人/发送邮箱定义在配置文件 config/mail.php 中。不过,我们可以使用from 方法为特定通知指定发送邮箱:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    return (new mailmessage)
                ->from('test@example.com', 'example')
                ->line('...');
}

自定义接收人

通过 mail 通道发送通知时,通知系统会自动在被通知实体上查找 email 属性,我们可以通过在该实体上定义一个 routenotificationformail 来自定义使用哪个邮箱地址发送通知:

email_address;
    }
}

自定义主题

默认情况下,邮件的主题就是格式为“标题风格”的通知类名,因此,如果通知类被命名为 invoicepaid,邮件的主题就是 invoice paid,如果你想要为消息指定明确的主题,可以在构建消息的时候调用 subject 方法:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    return (new mailmessage)
        ->subject('notification subject')
        ->line('...');
}

自定义邮件程序

默认情况下,将使用config/mail.php配置文件中定义的默认驱动程序发送电子邮件通知。但是,我们可以在运行时通过在构建消息时调用mailer方法来指定不同的邮件程序:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    return (new mailmessage)
                ->mailer('postmark')
                ->line('...');
}

自定义模板

我们可以通过发布通知扩展包的资源来修改邮件通知所使用的 html 和纯文本模板。运行完下面这个命令之后,邮件通知模板将会存放到 resources/views/vendor/notifications 目录:

$ php artisan vendor:publish --tag=laravel-notifications

预览邮件通知

设计邮件通知模板时,在浏览器中像 blade 模板那样快速预览渲染的邮件消息很方便,为此,laravel 允许你直接从路由闭包或控制器中返回任意通过邮件通知生成的邮件消息。当 mailmessage 被返回时,它将会被渲染并显示在浏览器中,以便你快速预览和调整,而不必真的发送一封邮件:

route::get('mail', function () {
    $invoice = app\invoice::find(1);
    return (new app\notifications\invoicepaid($invoice))
                ->tomail($invoice->user);
});

markdown 邮件通知

markdown 邮件通知允许你利用邮件通知的预置模板,从而让你可以自由编写更长、更具个性化的消息。因为这些消息以 markdown 格式编写,laravel 还可以为它们渲染出高颜值、响应式的 html 模板,同时自动生成纯文本的副本。

生成消息

要生成带有相应 markdown 模板的通知,可以在使用 artisan 命令 make:notification 时带上 --markdown 选项:

$ php artisan make:notification invoicepaid --markdown=mail.invoice.paid

和其他邮件通知一样,使用 markdown 模板的通知类也要定义一个 tomail 方法。不过,你可以使用 markdown 方法取代构造通知的 line 和 action 方法来指定要使用的 markdown 模板名称:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 * @translator laravelacademy.org
 */
public function tomail($notifiable)
{
    $url = ;
    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,
{{ config('app.name') }} @endcomponent

按钮组件

按钮组件渲染一个居中的按钮链接。该组件接收两个参数,url 和可选的 color,支持的颜色有 blude,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 通知组件到应用中进行自定义,要导出组件,使用 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 选项即可。

要为独立的通知自定义主题,可以在构建通知的邮件消息时调用 theme 方法,该方法接收发送通知时使用的主题名称作为参数:

/**
 * get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \illuminate\notifications\messages\mailmessage
 */
public function tomail($notifiable)
{
    return (new mailmessage)
                ->theme('invoice')
                ->subject('invoice paid')
                ->markdown('mail.invoice.paid', ['url' => $url]);
}

数据库通知

相关组件安装

database 通知通道会在数据表中存储通知信息,该表包含诸如通知类型以及用于描述通知的自定义 json 数据之类的信息。

我们可以在用户界面中查询这个数据表来展示通知,不过,在此之前,需要创建数据表来保存信息,我们可以使用 notifications:table命令来生成迁移文件然后以此生成相应数据表:

$ php artisan notifications:table
$ php artisan migrate

格式化数据库通知

如果一个通知支持存放在数据表,则需要在通知类中定义 todatabasetoarray 方法,该方法接收一个 $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 vs. toarray

toarray 方法还被 broadcast 通道用来判断广播什么数据到 javascript 客户端,如果你想要为 database 和 broadcast 通道提供两种不同的数组表示,则需要定义一个 todatabase 方法来取代 toarray 方法。

访问通知

通知被存放到数据表之后,需要在被通知实体中有一个便捷的方式来访问它们。laravel 默认提供的 app\user 模型引入的 illuminate\notifications\notifiable trait 包含了返回实体对应通知的 eloquent 关联关系方法 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;
}

注:要想从 javascript 客户端访问通知,需要在应用中定义一个通知控制器为指定被通知实体(比如当前用户)返回通知,然后从 javascript 客户端发送一个 http 请求到控制器对应 uri。

标记通知为已读

一般情况下,我们会将用户浏览过的通知标记为已读,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();

广播通知

准备工作

在进行广播通知之前,需要配置并了解事件广播服务,事件广播为 javascript 客户端响应服务端触发的事件铺平了道路。

格式化广播通知

broadcast 通道广播通知使用了 laravel 的事件广播服务,从而允许 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');

自定义通知类型

除了指定的数据之外,广播通知还包含一个 type 字段,用于包含通知的类名。如果想自定义提供给 javascript 客户端的type,可以在通知类上定义一个broadcasttype方法:

use illuminate\notifications\messages\broadcastmessage;
/**
 * get the type of the notification being broadcast.
 *
 * @return string
 */
public function broadcasttype()
{
    return 'broadcast.message';
}

监听通知

通知将会以格式化为 {notifiable}.{id} 的形式在私有频道上广播,因此,如果你要发送通知到 id 为 1 的 app\user 实例,那么该通知将会在私有频道 app.user.1 上进行广播,如果使用了laravel echo,可以使用辅助函数 notification 轻松在某个频道上监听通知:

echo.private('app.user.'   userid)
    .notification((notification) => {
        console.log(notification.type);
    });

自定义通知通道

如果想要自定义被通知实体在那个通道上接收广播通知,可以在被通知实体上定义一个 receivesbroadcastnotificationson 方法:

id;
    }
}

短信(sms)通知

相关准备

laravel 基于 nexmo 发送短信通知,在使用nexmo 发送通知前,需要安装对应 composer 依赖包 laravel/nexmo-notification-channel

$ composer require laravel/nexmo-notification-channel

安装上述依赖的同时也会安装 nexmo/laravel 扩展包,该扩展包会包含自己的配置文件,我们可以使用 nexmo_keynexmo_secret 环境变量来设置 nexmo 的公钥和私钥。

接下来,需要在配置文件 config/services.php 中添加相应配置,例如:

'nexmo' => [
    'sms_from' => '15556666666',
],

sms_from 配置项就是你用于发送短信消息的手机号码,你需要在 nexmo 控制面板中为应用生成一个手机号码。

格式化短信通知

如果通知支持以短信方式发送,需要在通知类上定义一个 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');
}

格式化验证码通知

laravel 还支持发送验证码通知,对应的消息模板可以在 nexmo 账户中预定义,可以指定通知类型(alert、2fa 或者 marketing),以及填充模板的自定义值:

/**
 * get the nexmo / shortcode representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toshortcode($notifiable)
{
    return [
        'type' => 'alert',
        'custom' => [
            'code' => 'abc123',
        ];
    ];
}

注:和短信通知路由一样,你需要在通知模型中实现 routenotificationforshortcode 方法。

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();
}

自定义来源号码

如果你要通过与配置文件 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');
}

短信通知路由

使用 nexmo 通道发送通知的时候,通知系统会自动在被通知实体上查找 phone_number 属性。如果你想要自定义通知被发送到的手机号码,可以在该实体上定义一个 routenotificationfornexmo 方法:

phone_number;
    }
}

slack 通知

相关准备工作

在通过 slack 发送通知前,必须通过 composer 安装对应的通知渠道扩展包:

$ composer require laravel/slack-notification-channel

此外,我们还要为 slack 组配置一个「incoming webhook」集成。该集成会在你进行 slack 通知路由的时候提供一个url。

格式化 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,最终创建的消息如下:

创建的简单文本的消息示例

自定义发送者 & 接收者

我们可以使用 fromto 方法自定义发送者和接收者,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');
}

slack 附件

我们还可以添加“附件”到 slack 消息。相对简单文本消息,附件可以提供更加丰富的格式选择。在这个例子中,我们会发送一个在应用程序中出现的异常错误通知,包含查看更多异常细节的链接:

/**
 * get the slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return slackmessage
 */
public function toslack($notifiable)
{
    $url = ;
    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 消息:

生成的slack消息

附件还允许我们指定要呈献给用户的数组数据。为了提高可读性,给定的数组会以表格形式展示:

/**
 * get the slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return slackmessage
 */
public function toslack($notifiable)
{
    $url = ;
    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 消息:

由数组形式的数据生成的slack消息

markdown 附件内容

如果一些附件字段包含 markdown,可以使用 markdown 方法来构建 slack 用以解析并显示以 markdown 格式编写的附件字段,该方法支持的值包括 pretext、text、/ 或 fields。想要了解更多关于 slack 格式化的信息,查看 slack api 文档:

/**
 * get the slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return slackmessage
 */
public function toslack($notifiable)
{
    $url = ;
    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 方法,这将会返回通知被发送到的 webhook url。webhook url 可通过在 slack 组上添加一个"incoming webhook" 服务来生成:

slack_webhook_url;
    }
}

本地化通知

和邮件类似,laravel 允许你通过本地化设置语言而非当前默认语言发送通知,甚至在通知队列中也能记住本地化设置。

为了实现这个功能,illuminate\notifications\notification 类提供了一个 locale 方法用于设置期望的语言。应用会在通知被格式化的时候切换到此次设置的本地化语言,格式化完成后,再切换回之前设置的本地化语言:

$user->notify((new invoicepaid($invoice))->locale('es'));

还可以通过 notification 门面同时为多个通知实体进行本地化语言设置:

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));

通知事件

当通知被发送后,通知系统会触发 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
}

自定义通道

通过上面的介绍,可见 laravel 为我们提供了多种通知通道,但是如果你想要编写自己的驱动以便通过其他通道发送通知,也很简单。首先定义一个包含 send 方法的类,该方法接收两个参数: $notifiable 和 $notification :

tovoice($notifiable);
        // send notification to the $notifiable instance...
    }
}

通知通道类被定义后,就可以在应用中通过 via 方法返回类名:

查看笔记

扫码一下
查看教程更方便
网站地图