はじめに
こちらの記事は、社内knowledgeからの移行記事になります。
初めての技術投稿で探り探りな面があります。
Laravelに搭載されている通知(Notifications)機能を使って、
ログインしたときにSlackに通知を送る機能を作成してみました。
不正ログイン通知や購入処理完了時のメッセージ送信などに使えそうですね。
【参考にした公式】
- 公式(英語)
- ReaDouble
なお、ログインイベントのリスナー設定は省略します。
GitHubにコードはあります。
環境
- Vagrant(Homestead)
- Laravel 5.8.23
Slackの設定
- 送信したいワークスペースの管理画面(https://[ワークスペース名].slack.com/apps) から、投稿したいチャンネルを選択してIncoming Webhookを追加する。
- 追加後の画面からWebhook URLを回収する。 ***
パッケージのインストール
composer require guzzlehttp/guzzle
composer require laravel/slack-notification-channel
通知クラスの作成
下記のコマンドでSlackという通知クラスが作成されます。
viaメソッドで複数定義するとどうなるかは試してみる。
php artisan make:notification Slack
通知クラス(App\Notifications\Slack)
Notification.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\SlackMessage;
class Slack extends Notification
{
use Queueable;
protected $content;
protected $channel;
protected $name;
/**
* Create a new notification instance.
* @param string $message
* @return void
*/
public function __construct(string $message)
{
$this->channel = env('SLACK_CHANNEL');
$this->name = env('SLACK_NAME');
$this->content = $message;
}
/**
* 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)
->from($this->name, ':ghost:')
->to($this->channel)
->content($this->content);
}
}
ログインイベントのリスナーを作成
ログイン時に通知を送信するためのクラスを作成する。
ログイン イベントリスナークラス(App\Listeners\LoginListener)
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use App\Notifications\Slack;
use App\Notification\Slack\SlackRepository;
use Illuminate\Support\Facades\Notification as FacNotification;
class LoginListener
{
protected $slackRepository;
/**
* Create the event listener.
*
* @param Request $request
* @param SlackRepository $slackRepository
*/
public function __construct(Request $request, SlackRepository $slackRepository)
{
$this->request = $request;
$this->slackRepository = $slackRepository;
}
/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Login $event)
{
//ログイン成功時の処理
// リポジトリで通知を送信します。
$this->slackRepository->notify(new Slack("リポジトリ:{$event->user->name}"));
// ファサードで通知を送信します。
FacNotification::route('slack', env('SLACK_WEBHOOK_URL'))
->notify(new Slack("ファサード:{$event->user->name}"));
// モデルで通知を送信します。
$event->user->notify(new Slack("モデル:{$event->user->name}"));
}
}
ログインすると...
絶対通知送信するマンに煽られる。
まとめ
- Laravelで通知機能を実装
- クラスから通知を出す場合
- 通知を送りたいクラスでNotifiableをtrait
- artisanコマンドで通知クラスを作る
- 通知クラスにviaメソッド,to〇〇メソッドを実装
- 通知を送りたいクラスにrouteNotificationFor〇〇メソッドを実装
- Notification ファサードを使う場合
use Illuminate\Support\Facades\Notification;
Notification::route($channel,$send)
->notify($clsNotification));
参考
その他の参考はこちら。