I am trying to send slack messages through laravel notification.
when events such as signed up
, leave
, and etc. happen using different channels.
But there's a problem here, because Laravel only supports one Hook URI or I just do not know how to set various channel Hook URIs.
How would I be able to send different kind of slack messages to different channels?
Thank you in advance.
Below is my signup notification codes :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;
/**
* Class SignedUp
* @package App\Notifications
*/
class SignedUp extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return [
'slack',
];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
return (new SlackMessage)
->success()
->content("Welcome");
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
}
And here is my user model code :
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Notifications\Notifiable;
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, Notifiable;
/**
* Route notifications for the Nexmo channel.
*
* @return string
*/
public function routeNotificationForSlack() : string
{
return 'slack webhook uri';
}
}
Add to Users.php
protected $webhook;
public function routeNotificationForSlack( ) {
if($this->webhook){
return config('slack.channels.'.$this->webhook);
}
}
public function slackChannel($channel){
$this->webhook = $channel;
return $this;
}
config/slack.php (create a slack.php file inside config)
return [
'channels' => [
'name-of-channel' => 'webhook-url-of-channel',
'name-of-next-channel' => 'webhook-url-of-next-channel'
]
];
To send notification to slack channel
$user->slackChannel('name-of-channel')->notify(new Notification());