Laravel5.3より、Notificationsという仕組みが備わったので、早速試してみます。
Laravel Notification Channelsで、利用できるチャンネルの一覧が確認できます。
Chatworkのライブラリがなかったので、勉強ついでに作ってみました。
Github, Packagistに公開しました。
e2kaneko/laravel-chatwork-notification: Chatwork Notifications Channel for Laravel 5.3
e2kaneko/laravel-chatwork-notifications – Packagist
つかってみます
composerに追加します。
composer require e2kaneko/laravel-chatwork-notifications
composer update後、config/app.phpに追記します。
'providers' => [
...
NotificationChannels\Chatwork\ChatworkServiceProvider::class,
],
config/services.phpにChatwork用の設定を追加します。
具体的には、以下のようにapi_tokenを書きます。
...
'chatwork' => [
'api_token' => env('CHATWORK_API_TOKEN'),
],
...
ここまでで、初期設定は完了。
artisanでNotificationsクラスを作成します。
php artisan make:notification ChatworkPosted
できました!
引数でオブジェクトを受け取って、メッセージを通知するように実装します。
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use NotificationChannels\Chatwork\ChatworkMessage;
use NotificationChannels\Chatwork\ChatworkInformation;
use NotificationChannels\Chatwork\ChatworkChannel;
class ChatworkPosted extends Notification
{
use Queueable;
public function __construct($message)
{
$this->message = $message;
}
public function via($notifiable)
{
return [ChatworkChannel::class];
}
public function toChatwork($notifiable)
{
return (new ChatworkMessage())->message($this->message->body);
}
}
UserクラスにNotifiableトレイトを設定して、通知先Room情報を設定します。
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function routeNotificationForChatwork()
{
return '99999999'; // chatwork room id
}
}
準備できました!
では、通知してみます。
$user = new User; $message = new stdClass(); $message->body = "✂-----------------12時----------------------------------------------"; $user->notify(new \App\Notifications\ChatworkPosted($message));
Chatworkに通知されました!
以下のように、NotificationクラスのFacadeを利用することもできます。
Notification::send($user, new \App\Notifications\ChatworkPosted($a));
とてもいい感じです










