Skip to content

Instantly share code, notes, and snippets.

@Shaz3e
Created September 10, 2024 19:32
Show Gist options
  • Save Shaz3e/e46ccf8b672325a7b51d9fdd98aad2bf to your computer and use it in GitHub Desktop.
Save Shaz3e/e46ccf8b672325a7b51d9fdd98aad2bf to your computer and use it in GitHub Desktop.
Send Slack Notification in Laravel 11
SLACK_BOT_USER_OAUTH_TOKEN=
SLACK_BOT_USER_DEFAULT_CHANNEL=
<?php
// app/Notification/OrderNotification.php
namespace App\Notifications;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock;
use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock;
use Illuminate\Notifications\Slack\SlackMessage;
class OrderNotification extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*/
public function __construct(public User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via($notifiable)
{
return ['slack'];
}
public function toSlack(object $notifiable): SlackMessage
{
return (new SlackMessage)
->to("#general") // set the channel
->text('Check & update status.')
->headerBlock('New User Created')
->contextBlock(function (ContextBlock $block) {
$block->text($this->user->name);
})
->sectionBlock(function (SectionBlock $block) {
$block->text($this->user->email);
$block->field($this->user->created_at);
})
->dividerBlock()
->sectionBlock(function (SectionBlock $block) {
$block->text('Congratulations!');
});;
}
}
<?php
// app/Services/SlackService.php
namespace App\Services;
class SlackService
{
public function send(string $message): void {}
}
<?php
use App\Models\User;
use App\Notifications\OrderNotification;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
// return view('welcome');
$user = User::create([
'name' => fake()->name(),
'email' => fake()->email(),
'password' => bcrypt('123456789'),
]);
$user->notify(new OrderNotification($user));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment