[英]How do you send a Slack Notification from a console command in Laravel?
It's very easy to send a Slack notification when a new record is created but how do you do it within an Artisan::command?创建新记录时发送 Slack 通知非常容易,但如何在 Artisan::command 中执行此操作?
Kernel.php Kernel.php
$schedule->command('vacationReminder')->daily()->at('07:00');
console.php控制台.php
Artisan::command('vacationReminder', function () {
$this->notify(new VacationReminder());
})->purpose('Remind employees who is on vacation');
I know the above is wrong but what do I need to fire off the Slack notification from console.php?我知道上面是错误的,但是我需要从 console.php 触发 Slack 通知吗? When I send from a model, for example, I need to import
例如,当我从 model 发送时,我需要导入
use Illuminate\Notifications\Notifiable;
use App\Notifications\VacationReminder;
and have the function并拥有 function
public function routeNotificationForSlack($notification)
{
return env('SLACK_NOTIFICATION_WEBHOOK');
}
How do these come into play when trying to send a notification from console.php?当尝试从 console.php 发送通知时,这些如何发挥作用?
It is recommended to use a config file to access ENV variables (instead of using env()
directly).建议使用配置文件来访问 ENV 变量(而不是直接使用
env()
)。 Create a config file config/notifications.php
with the following code:使用以下代码创建配置文件
config/notifications.php
:
<?php
return [
'slack' => env('SLACK_NOTIFICATION_WEBHOOK')
];
You can later access the config variable using config('notifications.slack')
.您可以稍后使用
config('notifications.slack')
访问配置变量。 Then in your console.php
you use the Notification facade and your VacationReminder notification by adding然后在你的
console.php
你使用 Notification 门面和你的 VacationReminder 通知通过添加
use Illuminate\Support\Facades\Notification;
use App\Notifications\VacationReminder;
at the top.在顶部。 Finally, create your command:
最后,创建您的命令:
Artisan::command('vacationReminder', function () {
Notification::route('slack', config('notifications.slack'))
->notify(new VacationReminder());
})->describe('Remind employees who is on vacation');
This uses On-Demand Notifications so you don't need to have a model with the Notifiable
trait.这使用按需通知,因此您不需要具有
Notifiable
特征的 model。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.