Laravelのインストール
$ laravel new SlackNotification
$ cd SlackNotification
guzzleライブラリのインストール
$ composer require guzzlehttp/guzzle
Webhook URLを取得
https://api.slack.com/incoming-webhooks
上記URLよりWebhookのURLを取得
Notificationの作成
$ php artisan make:notification SlackPost
下記のようにファイルを修正
app/Notifications/SlackPost.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\SlackMessage;
class SlackPost extends Notification
{
use Queueable;
public function via($notifiable)
{
return ['slack'];
}
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('こんにちは');
}
}
UserモデルにWebhhok URLを設定
取得したWebhook URLを設定
app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
//...
public function routeNotificationForSlack($notification)
{
return 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
}
}
テスト用コマンドを作成
$ php artisan make:command NotifySlack
下記のように編集
app/Console/Commands/NotifySlack.php
<?php
namespace App\Console\Commands;
use App\Notifications\SlackPost;
use App\User;
use Illuminate\Console\Command;
class NotifySlack extends Command
{
protected $signature = 'notify:slack';
protected $description = 'Slackへテスト送信';
public function handle()
{
$user = new User();
$user->notify(new SlackPost());
}
}
コマンドを実行
$ php artisan notify:slack
メッセージ内容を修正
app/Notifications/SlackPost.php
//...
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('ららべる')
->image('https://laravel.com/favicon.png')
->content('こんにちは');
}
//...
app/Notifications/SlackPost.php
//...
public function toSlack($notifiable)
{
$url = 'https://qiita.com';
return (new SlackMessage)
->from('きーた')
->image('https://cdn.qiita.com/assets/favicons/public/apple-touch-icon-f9a6afad761ec2306e10db2736187c8b.png')
->success()
->attachment(function ($attachment) use ($url) {
$attachment->title('Qiita', $url)
->fields([
'タイトル' => 'LaravelでSlack Notification',
'タグ' => '入門',
'ユーザー' => '@kei4eva4',
'投稿日時' => \Carbon\Carbon::now()->toDateTimeString()
]);
});
}
//...