Search code examples
phplaravellaravel-5slacklaravel-5.8

Laravel Slack on-demand notification; where to set the webhook?


As per the Laravel docs I can do an on-demand notification in a controller like this:

use Notification;
use App\Notifications\TradeSuccessful;

$trada_data = array( 'title' => 'test', 'amount' => 123.45 )

Notification::route('slack', '#test')->notify(new TradeSuccessful($trade_data));

And in TradeSuccessful (example code):

public function toSlack($notifiable)
    {
        return (new SlackMessage)
            ->success()
            ->content('One of your invoices has been paid!')
            ->attachment(function ($attachment) use ($trade_data) {
                $attachment->title('Invoice 1322')
                    ->fields([
                    'Title' => $trade_data['title],
                    'Amount' => $trade_data['amount]
                ]);
            });
    }

Main question: when I use Notifications like this (on demand), where do I set the Slack webhook? Because in the documentation they use:

public function routeNotificationForSlack($notification)
    {
        return 'https://hooks.slack.com/services/...';
    }

But that function is defined on a Model, and when using on demand notifications nothing is defined on a Model.


Solution

  • From the documentation:

    On-Demand Notifications

    Sometimes you may need to send a notification to someone who is not stored as a "user" of your application. Using the Notification::route method, you may specify ad-hoc notification routing information before sending the notification:

    Notification::route('mail', '[email protected]')
                ->route('vonage', '5555555555')
                ->notify(new InvoicePaid($invoice));
    

    In the case of Slack, the route you specify needs to be the webhook:

    use Notification;
    use App\Notifications\TradeSuccessful;
    
    $tradeData = [
        'title' => 'test',
        'amount' => 123.45,
    ];
    
    $slackWebhook = 'my-slack-webhook-url'; // <---
    
    Notification::route('slack', $slackWebhook)->notify(new TradeSuccessful($tradeData));
                                 ^^^^^^^^^^^^^
    

    Of course, you should store is as a config key, but you get the idea.