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?
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');
I know the above is wrong but what do I need to fire off the Slack notification from console.php? When I send from a model, for example, I need to import
use Illuminate\Notifications\Notifiable;
use App\Notifications\VacationReminder;
and have the 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?
CodePudding user response:
It is recommended to use a config file to access ENV variables (instead of using env()
directly). Create a config file config/notifications.php
with the following code:
<?php
return [
'slack' => env('SLACK_NOTIFICATION_WEBHOOK')
];
You can later access the config variable using config('notifications.slack')
. Then in your console.php
you use the Notification facade and your VacationReminder notification by adding
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.