如何从Laravel中的控制台命令发送Slack通知



创建新记录时发送Slack通知非常容易,但如何在Artisan::命令中执行?

Kernel.php

$schedule->command('vacationReminder')->daily()->at('07:00');

console.php

Artisan::command('vacationReminder', function () {
$this->notify(new VacationReminder());
})->purpose('Remind employees who is on vacation');

我知道上面的内容是错误的,但我需要什么才能从console.php发出Slack通知?例如,当我从模型发送时,我需要导入

use IlluminateNotificationsNotifiable;
use AppNotificationsVacationReminder;

并具有功能

public function routeNotificationForSlack($notification)
{
return env('SLACK_NOTIFICATION_WEBHOOK');
}

当尝试从console.php发送通知时,这些是如何发挥作用的?

建议使用配置文件访问ENV变量(而不是直接使用env()(。使用以下代码创建配置文件config/notifications.php

<?php
return [
'slack' => env('SLACK_NOTIFICATION_WEBHOOK')
];

稍后可以使用config('notifications.slack')访问配置变量。然后在您的console.php中,您通过添加来使用Notification外观和VacationReminder通知

use IlluminateSupportFacadesNotification;
use AppNotificationsVacationReminder;

顶部。最后,创建您的命令:

Artisan::command('vacationReminder', function () {
Notification::route('slack', config('notifications.slack'))
->notify(new VacationReminder());
})->describe('Remind employees who is on vacation');

这使用了按需通知,因此您不需要具有Notifiable特性的模型。

最新更新