LoginSignup
28
17

More than 5 years have passed since last update.

Laravel5.3 NotificationsでSlackに通知してみる

Posted at

概要

Laravel5.3からNotifications - Laravel - The PHP Framework For Web Artisans が追加され、ユーザ通知機能がたいへん簡単に実装できるようになりました。

今回はhttp://localhost:8000にアクセスされたらSlackにメッセージを飛ばすという簡単な機能を実装します。

Laravel5.3のインストール

Guzzleを追加する

  • Guzzleとは
    • PHPのHTTPクライアントライブラリ
  • DLしたLaravelのディレクトリの直下で下記のコマンドを実行し、パッケージを追加する
$ composer require guzzlehttp/guzzle

Notificationクラスの作成

  • artisanコマンドでNotificationクラスを生成する
    • app/Notifications/SlackPosted.php
$ php artisan make:notification SlackPosted    
Notification created successfully.

Notificationクラスの修正

通知するサービスの追加

  • viaメソッドを編集する
  • 通知するサービス名にslackを追加する
app/Notifications/SlackPosted.php
<?php
class SlackPosted extends Notification
{
    public function via($notifiable)
    {
        return ['slack'];
    }
}

Slackに通知するメッセージの作成

app/Notifications/SlackPosted.php
use Illuminate\Notifications\Messages\SlackMessage;
public function toSlack($notifiable)
{
    return (new SlackMessage)
        ->success()
        ->content('問題が発生しました')
        ->attachment(function ($attachment) {
            $attachment->title('weeklyランキングが生成されませんでした。')
                ->content('エラーログ。。。');
        });
}

上記の記述で実際にSlackに通知されるメッセージはこんな感じ。

スクリーンショット 2016-09-03 16.31.04.png

routeNotificationForSlackメソッドの追加

  • SlackのWebHook URLを返すrouteNotificationForSlackメソッドを追加する
  • routeNotificationForXXX
    • XXXの部分書かれたサービス名をもとに、Laravelが自動的にドライバ情報を読み込んでくれる
app/User.php
public function routeNotificationForSlack()
{
        return 'https://hooks.slack.com/services/xxxx/xxxx/xxxx';
}

ルーティングの修正

  • /にアクセスがあった時にnotifyメソッドでユーザに通知する
  • notifyメソッドはNotificationクラスのインスタンスを受け取り、通知する
routes/web.php
Route::get('/', function () {
    $user = new App\User;
    $user->notify(new \App\Notifications\SlackPosted);
});

あとはphp artisan serveで起動し、http://localhost:8000にアクセスするとSlackにメッセージが届くはずです!

参考記事

リリース直前! Laravel 5.3 の変更点(新機能編)
http://tech.innovator.jp.net/entry/2016/08/17/115629

Send Slack Notifications With Laravel in Minutes
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/11

Notifications - Laravel - The PHP Framework For Web Artisans
https://laravel.com/docs/5.3/notifications

28
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
17