イントロダクションIntroduction
最近の多くのWebアプリケーションでは、WebSocketを使用して、リアルタイムのライブ更新ユーザーインターフェイスを実装しています。サーバ上で一部のデータが更新されると、通常、メッセージはWebSocket接続を介して送信され、クライアントによって処理されます。WebSocketは、UIに反映する必要のあるデータの変更をアプリケーションのサーバから継続的にポーリングするよりも、効率的な代替手段を提供しています。In many modern web applications, WebSockets are used to implement realtime, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a WebSocket connection to be handled by the client. WebSockets provide a more efficient alternative to continually polling your application's server for data changes that should be reflected in your UI.
たとえば、アプリケーションがユーザーのデータをCSVファイルにエクスポートして電子メールで送信できると想像してください。ただ、このCSVファイルの作成には数分かかるため、キュー投入するジョブ内でCSVを作成し、メールで送信することを選択したとしましょう。CSVを作成しユーザーにメール送信したら、イベントブロードキャストを使用して、アプリケーションのJavaScriptで受信するApp\Events\UserDataExported
イベントをディスパッチできます。イベントを受信したら、ページを更新することなく、CSVをメールで送信済みであるメッセージをユーザーへ表示できます。For example, imagine your
application is able to export a user's data to a CSV
file and email it to them. However, creating this
CSV file takes several minutes so you choose to
create and mail the CSV within a queued
job[/docs/{{version}}/queues]. When the CSV
has been created and mailed to the user, we can use
event broadcasting to dispatch an
App\Events\UserDataExported
event that
is received by our application's JavaScript. Once
the event is received, we can display a message to
the user that their CSV has been emailed to them
without them ever needing to refresh the
page.
こうした機能の構築を支援するため、LaravelはWebSocket接続を介してサーバ側のLaravelイベントを簡単に「ブロードキャスト」できます。Laravelイベントをブロードキャストすると、サーバ側のLaravelアプリケーションとクライアント側のJavaScriptアプリケーション間で同じイベント名とデータを共有できます。To assist you in building these types of features, Laravel makes it easy to "broadcast" your server-side Laravel events[/docs/{{version}}/events] over a WebSocket connection. Broadcasting your Laravel events allows you to share the same event names and data between your server-side Laravel application and your client-side JavaScript application.
ブロードキャストの基本的なコンセプトは簡単で、クライアントはフロントエンドで指定したチャンネルへ接続し、Laravelアプリケーションはバックエンドでこれらのチャンネルに対し、イベントをブロードキャストします。こうしたイベントには、フロントエンドで利用する追加データを含められます。The core concepts behind broadcasting are simple: clients connect to named channels on the frontend, while your Laravel application broadcasts events to these channels on the backend. These events can contain any additional data you wish to make available to the frontend.
サポートしているドライバSupported Drivers
Laravelはデフォルトで、3つのサーバサイド・ブロードキャストドライバを用意しています。Laravel Reverb、Pusher Channels、Ablyです。By default, Laravel includes three server-side broadcasting drivers for you to choose from: Laravel Reverb[https://reverb.laravel.com], Pusher Channels[https://pusher.com/channels], and Ably[https://ably.com].
イベントとリスナに関するLaravelのドキュメントをしっかりと読んでください。[!NOTE]
Note: イベントブロードキャストに取り掛かる前に、
Before diving into event broadcasting, make sure you have read Laravel's documentation on events and listeners[/docs/{{version}}/events].
サーバ側インストールServer Side Installation
Laravelのイベントブロードキャストの使用を開始するには、Laravelアプリケーション内でいくつかの設定を行い、いくつかのパッケージをインストールする必要があります。To get started using Laravel's event broadcasting, we need to do some configuration within the Laravel application as well as install a few packages.
イベントブロードキャストは、Laravel Echo(JavaScriptライブラリ)がブラウザクライアント内でイベントを受信できるように、Laravelイベントをブロードキャストするサーバ側ブロードキャストドライバによって実行されます。心配いりません。以降から、インストール手順の各部分を段階的に説明します。Event broadcasting is accomplished by a server-side broadcasting driver that broadcasts your Laravel events so that Laravel Echo (a JavaScript library) can receive them within the browser client. Don't worry - we'll walk through each part of the installation process step-by-step.
設定Configuration
アプリケーションのイベントブロードキャスト設定はすべてconfig/broadcasting.php
設定ファイルに保存されます。アプリケーションの中にこのファイルがなくても、心配ありません。install:broadcasting
Artisanコマンドを実行するで作成できます。All of
your application's event broadcasting configuration
is stored in the
config/broadcasting.php
configuration
file. Don't worry if this directory does not exist
in your application; it will be created when you run
the install:broadcasting
Artisan
command.
Laravelはいくつかのブロードキャストドライバをあらかじめサポートしています。 Laravel Reverb、Pusher
Channels、Ably、ローカル開発とデバッグ用のlog
ドライバです。さらに、テスト中にブロードキャストを完全に
無効にできる、null
ドライバも用意しています。これらの各ドライバの設定例は、config/broadcasting.php
設定ファイルにあります。Laravel supports several
broadcast drivers out of the box: Laravel
Reverb[/docs/{{version}}/reverb], Pusher
Channels[https://pusher.com/channels],
Ably[https://ably.com], and a
log
driver for local development and
debugging. Additionally, a null
driver
is included which allows you to disable broadcasting
during testing. A configuration example is included
for each of these drivers in the
config/broadcasting.php
configuration
file.
インストールInstallation
新しいLaravelアプリケーションでブロードキャストは、デフォルトで有効になっていません。ブロードキャストを有効にするには、install:broadcasting
Artisanコマンドを使用します。By default,
broadcasting is not enabled in new Laravel
applications. You may enable broadcasting using the
install:broadcasting
Artisan
command:
php artisan install:broadcasting
install:broadcasting
コマンドを実行すると、config/broadcasting.php
ファイルができます。更に、routes/channels.php
ファイルも生成され、これでアプリケーションのブロードキャスト認可ルートとコールバックを登録します。The
install:broadcasting
command will
create the config/broadcasting.php
configuration file. In addition, the command will
create the routes/channels.php
file
where you may register your application's broadcast
authorization routes and callbacks.
キュー設定Queue Configuration
イベントをブロードキャストする前に、まずキューワーカを設定し、実行する必要があります。すべてのイベントブロードキャストはキュー投入するジョブを介して実行されるため、イベントをブロードキャストしても、アプリケーションのレスポンスタイムに深刻な影響を与えません。Before broadcasting any events, you should first configure and run a queue worker[/docs/{{version}}/queues]. All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected by events being broadcast.
ReverbReverb
install:broadcasting
コマンドを実行すると、Laravel
Reverbをインストールするよう促されます。もちろん、Composerパッケージマネージャを使い、手作業でReverbをインストールすることもできます。Reverbは現在ベータ版なため、明示的にベータリリースをインストールする必要があります。When running the
install:broadcasting
command, you will
be prompted to install Laravel
Reverb[/docs/{{version}}/reverb]. Of course,
you may also install Reverb manually using the
Composer package manager. Since Reverb is currently
in beta, you will need to explicitly install the
beta release:
composer require laravel/reverb:@beta
パッケージをインストールしたら、Reverbのインストールコマンドを実行して設定をリソース公開し、Reverbに必要な環境変数を追加して、アプリケーションでイベントブロードキャストを有効にします。Once the package is installed, you may run Reverb's installation command to publish the configuration, add Reverb's required environment variables, and enable event broadcasting in your application:
php artisan reverb:install
Reverbのインストールと使い方の詳しい説明は、Reverbのドキュメントにあります。You can find detailed Reverb installation and usage instructions in the Reverb documentation[/docs/{{version}}/reverb].
PusherチャンネルPusher Channels
Pusherチャンネルを使用してイベントをブロードキャストする場合は、Composerパッケージマネージャを使用してPusher Channels PHP SDKをインストールする必要があります。If you plan to broadcast your events using Pusher Channels[https://pusher.com/channels], you should install the Pusher Channels PHP SDK using the Composer package manager:
composer require pusher/pusher-php-server
次に、config/broadcasting.php
設定ファイルで、Pusher
Channelsの認証情報を設定します。このファイルはPusher
Channelsの設定例をあらかじめ含んでおり、キー、シークレット、アプリケーションIDを素早く指定できます。通常、Pusher
Channelsの認証情報はアプリケーションの.env
ファイルで設定します:Next, you should configure your
Pusher Channels credentials in the
config/broadcasting.php
configuration
file. An example Pusher Channels configuration is
already included in this file, allowing you to
quickly specify your key, secret, and application
ID. Typically, you should configure your Pusher
Channels credentials in your application's
.env
file:
PUSHER_APP_ID="your-pusher-app-id"
PUSHER_APP_KEY="your-pusher-key"
PUSHER_APP_SECRET="your-pusher-secret"
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME="https"
PUSHER_APP_CLUSTER="mt1"
config/broadcasting.php
ファイルのpusher
設定では、クラスターなどチャンネルでサポートされている追加のoptions
を指定することもできます。The
config/broadcasting.php
file's
pusher
configuration also allows you to
specify additional options
that are
supported by Channels, such as the
cluster.
次に、アプリケーションの.env
ファイルでBROADCAST_CONNECTION
環境変数をpusher
に設定します。Then, set the
BROADCAST_CONNECTION
environment
variable to pusher
in your
application's .env
file:
BROADCAST_CONNECTION=pusher
これで、クライアント側でブロードキャストイベントを受信するLaravel Echoをインストールして設定する準備が整いました。Finally, you are ready to install and configure Laravel Echo[#client-side-installation], which will receive the broadcast events on the client-side.
AblyAbly
AblyのLaravelブロードキャスターのドキュメントを参照してください。[!NOTE]
Note: 以下のドキュメントでは、Ablyを「Pusher互換」モードで使用する方法について説明していきます。しかし、Ablyチームは、Ablyが提供するユニークな機能を活用できるブロードキャスターとEchoクライアントを推奨し、保守しています。Ablyが保守するドライバの使用に関する詳細については、
The documentation below discusses how to use Ably in "Pusher compatibility" mode. However, the Ably team recommends and maintains a broadcaster and Echo client that is able to take advantage of the unique capabilities offered by Ably. For more information on using the Ably maintained drivers, please consult Ably's Laravel broadcaster documentation[https://github.com/ably/laravel-broadcaster].
Ablyを使用してイベントをブロードキャストする場合は、Composerパッケージマネージャを使用してAbly PHP SDKをインストールする必要があります。If you plan to broadcast your events using Ably[https://ably.com], you should install the Ably PHP SDK using the Composer package manager:
composer require ably/ably-php
次に、config/broadcasting.php
設定ファイルでAblyの接続資格情報を設定する必要があります。Ablyの設定例はすでにこのファイルに用意されているため、キーを手軽に指定できます。通常、この値はABLY_KEY
環境変数により設定する必要があります。Next, you should configure your
Ably credentials in the
config/broadcasting.php
configuration
file. An example Ably configuration is already
included in this file, allowing you to quickly
specify your key. Typically, this value should be
set via the ABLY_KEY
environment
variable[/docs/{{version}}/configuration#environment-configuration]:
ABLY_KEY=your-ably-key
次に、アプリケーションの.env
ファイルで
BROADCAST_CONNECTION
環境変数をably
に設定します。Then, set the
BROADCAST_CONNECTION
environment
variable to ably
in your application's
.env
file:
BROADCAST_CONNECTION=ably
これで、クライアント側でブロードキャストイベントを受信するLaravel Echoをインストールして設定する準備が整いました。Finally, you are ready to install and configure Laravel Echo[#client-side-installation], which will receive the broadcast events on the client-side.
クライアント側インストールClient Side Installation
ReverbReverb
Laravel
Echoは、サーバサイドのブロードキャストドライバによりブロードキャストされるチャンネルやイベントを簡単にサブスクライブできるJavaScriptライブラリです。EchoはNPMパッケージマネージャでインストールできます。以下の紹介例では、ReverbがWebSocketサブスクリプション、チャンネル、メッセージにPusherプロトコルを利用しているため、pusher-js
パッケージもインストールします。Laravel
Echo[https://github.com/laravel/echo] is a
JavaScript library that makes it painless to
subscribe to channels and listen for events
broadcast by your server-side broadcasting driver.
You may install Echo via the NPM package manager. In
this example, we will also install the
pusher-js
package since Reverb utilizes
the Pusher protocol for WebSocket subscriptions,
channels, and messages:
npm install --save-dev laravel-echo pusher-js
Echoをインストールしたら、アプリケーションのJavaScriptで新しいEchoインスタンスを生成します。これを行うのに最適な場所は、Laravelフレームワークに用意してある、resources/js/bootstrap.js
ファイルの一番下です。デフォルトでは、Echoの設定例をあらかじめこのファイルに用意してあります。コメントを解除し、broadcaster
設定オプションをreverb
に更新するだけです。Once Echo is installed, you are
ready to create a fresh Echo instance in your
application's JavaScript. A great place to do this
is at the bottom of the
resources/js/bootstrap.js
file that is
included with the Laravel framework. By default, an
example Echo configuration is already included in
this file - you simply need to uncomment it and
update the broadcaster
configuration
option to reverb
:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT,
wssPort: import.meta.env.VITE_REVERB_PORT,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});
次に、アプリケーションのアセットをコンパイルします。Next, you should compile your application's assets:
npm run build
Warning! Laravel Echoの
reverb
ブロードキャスターには、laravel-echo v1.16.0以上が必要です。[!WARNING]
The Laravel Echoreverb
broadcaster requires laravel-echo v1.16.0 .
PusherチャンネルPusher Channels
Laravel
Echoは、サーバサイドのブロードキャストドライバにより、ブロードキャストされるチャンネルやイベントを簡単にサブスクライブできるJavaScriptライブラリです。また、Echoはpusher-js
NPMパッケージを利用して、WebSocketサブスクリプション、チャンネル、メッセージ用のPusherプロトコルを実装しています。Laravel
Echo[https://github.com/laravel/echo] is a
JavaScript library that makes it painless to
subscribe to channels and listen for events
broadcast by your server-side broadcasting driver.
Echo also leverages the pusher-js
NPM
package to implement the Pusher protocol for
WebSocket subscriptions, channels, and
messages.
install:broadcasting
Artisanのコマンドは、自動的にlaravel-echo
とpusher-js
パッケージをインストールしますが、NPMを使用し手作業でインストールすることもできます。The
install:broadcasting
Artisan command
automatically installs the laravel-echo
and pusher-js
packages for you;
however, you may also install these packages
manually via NPM:
npm install --save-dev laravel-echo pusher-js
Echoをインストールしたら、アプリケーションのJavaScriptで新しいEchoインスタンスを生成する準備が整いました。install:broadcasting
コマンドはresources/js/echo.js
へ、Echoの設定ファイルを作成しますが、このファイルのデフォルト設定はLaravel
Reverb用のものです。以下の設定をコピーしてPusher用へ移行できます。Once Echo is installed, you are
ready to create a fresh Echo instance in your
application's JavaScript. The
install:broadcasting
command creates an
Echo configuration file at
resources/js/echo.js
; however, the
default configuration in this file is intended for
Laravel Reverb. You may copy the configuration below
to transition your configuration to
Pusher:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true
});
次に、アプリケーションの.env
ファイルで、Pusherの環境変数に適切な値を定義します。これらの変数が、.env
ファイルに存在していない場合は、追加してください。Next, you should define the
appropriate values for the Pusher environment
variables in your application's .env
file. If these variables do not already exist in
your .env
file, you should add
them:
PUSHER_APP_ID="your-pusher-app-id"
PUSHER_APP_KEY="your-pusher-key"
PUSHER_APP_SECRET="your-pusher-secret"
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME="https"
PUSHER_APP_CLUSTER="mt1"
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
アプリケーションのニーズに応じてEchoの設定を調整したら、アプリケーションのアセットをコンパイルしてください。Once you have adjusted the Echo configuration according to your application's needs, you may compile your application's assets:
npm run build
Viteドキュメントを参照してください。[!NOTE]
Note: アプリケーションで使用しているJavaScriptリソースのコンパイルについて詳しく知りたい場合は、
To learn more about compiling your application's JavaScript assets, please consult the documentation on Vite[/docs/{{version}}/vite].
既存のクライアントインスタンスの使用Using an Existing Client Instance
Echoで利用したい事前設定済みのPusherチャンネルクライアントインスタンスがすでにある場合は、client
設定オプションによりEchoへ渡せます。If you already have a
pre-configured Pusher Channels client instance that
you would like Echo to utilize, you may pass it to
Echo via the client
configuration
option:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
const options = {
broadcaster: 'pusher',
key: 'your-pusher-channels-key'
}
window.Echo = new Echo({
...options,
client: new Pusher(options.key, options)
});
AblyAbly
AblyのLaravelブロードキャスターのドキュメントを参照してください。[!NOTE]
Note: 以下のドキュメントでは、Ablyを「Pusher互換」モードで使用する方法について説明していきます。しかし、Ablyチームは、Ablyが提供するユニークな機能を活用できるブロードキャスターとEchoクライアントを推奨し、保守しています。Ablyが保守するドライバの使用に関する詳細については、
The documentation below discusses how to use Ably in "Pusher compatibility" mode. However, the Ably team recommends and maintains a broadcaster and Echo client that is able to take advantage of the unique capabilities offered by Ably. For more information on using the Ably maintained drivers, please consult Ably's Laravel broadcaster documentation[https://github.com/ably/laravel-broadcaster].
Laravel
Echoは、サーバサイドのブロードキャストドライバによりブロードキャストされるチャンネルやイベントを簡単に購読できるJavaScriptライブラリです。また、Echoは
pusher-js
NPMパッケージを利用して、WebSocketサブスクリプション、チャンネル、メッセージ用のPusherプロトコルを実装しています。Laravel
Echo[https://github.com/laravel/echo] is a
JavaScript library that makes it painless to
subscribe to channels and listen for events
broadcast by your server-side broadcasting driver.
Echo also leverages the pusher-js
NPM
package to implement the Pusher protocol for
WebSocket subscriptions, channels, and
messages.
install:broadcasting
Artisanのコマンドは、自動的にlaravel-echo
とpusher-js
パッケージをインストールしますが、NPMを使用し手作業でインストールすることもできます。The
install:broadcasting
Artisan command
automatically installs the laravel-echo
and pusher-js
packages for you;
however, you may also install these packages
manually via NPM:
npm install --save-dev laravel-echo pusher-js
続行する前に、Ablyアプリケーション設定でPusherプロトコルサポートを有効にする必要があります。この機能は、Ablyアプリケーションの設定ダッシュボードの「プロトコルアダプター設定」部分で有効にできます。Before continuing, you should enable Pusher protocol support in your Ably application settings. You may enable this feature within the "Protocol Adapter Settings" portion of your Ably application's settings dashboard.
Echoをインストールしたら、アプリケーションのJavaScriptで新しいEchoインスタンスを生成する準備が整いました。install:broadcasting
コマンドはresources/js/echo.js
へEchoの設定ファイルを作成しますが、このファイルのデフォルト設定はLaravel
Reverb用のものです。以下の設定をコピーして、設定をAbly用へ移行できます。Once Echo is installed, you are
ready to create a fresh Echo instance in your
application's JavaScript. The
install:broadcasting
command creates an
Echo configuration file at
resources/js/echo.js
; however, the
default configuration in this file is intended for
Laravel Reverb. You may copy the configuration below
to transition your configuration to Ably:
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_ABLY_PUBLIC_KEY,
wsHost: 'realtime-pusher.ably.io',
wsPort: 443,
disableStats: true,
encrypted: true,
});
Ably
Echoの設定が、VITE_ABLY_PUBLIC_KEY
環境変数を参照していることにお気づきかもしれません。この変数の値は、あなたのAbly公開鍵でなければなりません。あなたの公開鍵は、Ably鍵の:
文字の前にある部分です。You may have noticed our Ably
Echo configuration references a
VITE_ABLY_PUBLIC_KEY
environment
variable. This variable's value should be your Ably
public key. Your public key is the portion of your
Ably key that occurs before the :
character.
ニーズに合わせ、Echoの設定を調整したら、アプリケーションのアセットをコンパイルしてください。Once you have adjusted the Echo configuration according to your needs, you may compile your application's assets:
npm run dev
Viteドキュメントを参照してください。[!NOTE]
Note: アプリケーションで使用しているJavaScriptリソースのコンパイルについて詳しく知りたい場合は、
To learn more about compiling your application's JavaScript assets, please consult the documentation on Vite[/docs/{{version}}/vite].
概論Concept Overview
Laravelのイベントブロードキャストを使用すると、WebSocketに対するドライバベースのアプローチを使用して、サーバ側のLaravelイベントをクライアント側のJavaScriptアプリケーションへブロードキャストできます。現在、LaravelはPusherチャンネルとAblyドライバを用意しています。イベントは、Laravel Echo JavaScriptパッケージを用い、クライアント側で簡単に利用できます。Laravel's event broadcasting allows you to broadcast your server-side Laravel events to your client-side JavaScript application using a driver-based approach to WebSockets. Currently, Laravel ships with Pusher Channels[https://pusher.com/channels] and Ably[https://ably.com] drivers. The events may be easily consumed on the client-side using the Laravel Echo[#client-side-installation] JavaScript package.
イベントは「チャンネル」を介してブロードキャストされます。チャンネルは、パブリックまたはプライベートとして指定できます。アプリケーションへの訪問者は全員、認証や認可なしにパブリックチャンネルをサブスクライブできます。ただし、プライベートチャンネルをサブスクライブするには、ユーザーが認証され、そのチャンネルをリッスンする認可を持っている必要があります。Events are broadcast over "channels", which may be specified as public or private. Any visitor to your application may subscribe to a public channel without any authentication or authorization; however, in order to subscribe to a private channel, a user must be authenticated and authorized to listen on that channel.
サンプルアプリケーションの使用Using an Example Application
イベントブロードキャストの各コンポーネントに飛び込む前に、eコマースストアのサンプルを使用して概要を説明しましょう。Before diving into each component of event broadcasting, let's take a high level overview using an e-commerce store as an example.
このアプリケーションでは、ユーザーが注文の配送ステータスを表示できるページがあると仮定します。また、出荷ステータスの更新がアプリケーションによって処理されるときに、OrderShipmentStatusUpdated
イベントが発生すると仮定します。In our application, let's assume
we have a page that allows users to view the
shipping status for their orders. Let's also assume
that an OrderShipmentStatusUpdated
event is fired when a shipping status update is
processed by the application:
use App\Events\OrderShipmentStatusUpdated;
OrderShipmentStatusUpdated::dispatch($order);
ShouldBroadcast
インターフェイスThe ShouldBroadcast
Interface
ユーザーが注文の1つを表示しているときに、ステータスの更新を表示するためにページを更新する必要はありません。その代わりに、発生時にアプリケーションへ更新をブロードキャストしたいと思います。したがって、OrderShipmentStatusUpdated
イベントをShouldBroadcast
インターフェイスでマークする必要があります。これにより、イベントが発生したときにイベントをブロードキャストするようにLaravelへ指示します。When a user is viewing one of
their orders, we don't want them to have to refresh
the page to view status updates. Instead, we want to
broadcast the updates to the application as they are
created. So, we need to mark the
OrderShipmentStatusUpdated
event with
the ShouldBroadcast
interface. This
will instruct Laravel to broadcast the event when it
is fired:
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class OrderShipmentStatusUpdated implements ShouldBroadcast
{
/**
* 注文インスタンス
*
* @var \App\Order
*/
public $order;
}
ShouldBroadcast
インターフェイスは、イベントに対しbroadcastOn
メソッドを定義するよう要求します。このメソッドは、イベントがブロードキャストする必要があるチャンネルを返す役割を持っています。このメソッドの空のスタブは、生成したイベントクラスですでに定義済みなため、詳細を入力するだけで済みます。注文の作成者だけがステータスの更新を表示できるようにしたいので、その注文に関連付いたプライベートチャンネルでイベントをブロードキャストします。The ShouldBroadcast
interface requires our event to define a
broadcastOn
method. This method is
responsible for returning the channels that the
event should broadcast on. An empty stub of this
method is already defined on generated event
classes, so we only need to fill in its details. We
only want the creator of the order to be able to
view status updates, so we will broadcast the event
on a private channel that is tied to the
order:
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
/**
* イベントをブロードキャストするチャンネルを取得
*/
public function broadcastOn(): Channel
{
return new PrivateChannel('orders.'.$this->order->id);
}
イベントを複数のチャンネルでブロードキャストしたい場合は、代わりにarray
を返してください。If you wish the event to
broadcast on multiple channels, you may return an
array
instead:
use Illuminate\Broadcasting\PrivateChannel;
/**
* イベントをブロードキャストするチャンネルを取得
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('orders.'.$this->order->id),
// ...
];
}
チャンネルの認可Authorizing Channels
プライベートチャンネルをリッスンするには、ユーザーが認可されていなければならないことを忘れないでください。チャンネルの認可ルールは、アプリケーションのroutes/channels.php
ファイルで定義できます。この例では、orders.1
というプライベートチャンネルをリッスンするユーザーが、実際にそのオーダーの作成者であることを確認しています。Remember, users must be
authorized to listen on private channels. We may
define our channel authorization rules in our
application's routes/channels.php
file.
In this example, we need to verify that any user
attempting to listen on the private
orders.1
channel is actually the
creator of the order:
use App\Models\Order;
use App\Models\User;
Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) {
return $user->id === Order::findOrNew($orderId)->user_id;
});
channel
メソッドは、チャンネルの名前と、ユーザーがチャンネルでのリッスンを許可されているかどうかを示すtrue
またはfalse
を返すコールバックの2つの引数を取ります。The channel
method
accepts two arguments: the name of the channel and a
callback which returns true
or
false
indicating whether the user is
authorized to listen on the channel.
すべての認可コールバックは、現在認証されているユーザーを最初の引数として受け取り、追加のワイルドカードパラメーターを後続の引数として受け取ります。この例では、{orderId}
プレースホルダーを使用して、チャンネル名の「ID」部分がワイルドカードであることを示しています。All authorization callbacks
receive the currently authenticated user as their
first argument and any additional wildcard
parameters as their subsequent arguments. In this
example, we are using the {orderId}
placeholder to indicate that the "ID"
portion of the channel name is a
wildcard.
イベントブロードキャストのリッスンListening for Event Broadcasts
他に残っているのは、JavaScriptアプリケーションでイベントをリッスンすることだけです。Laravel
Echoを使用してこれを行えます。まず、private
メソッドを使用し、プライベートチャンネルをサブスクライブします。次に、listen
メソッドを使用してOrderShipmentStatusUpdated
イベントをリッスンします。デフォルトでは、イベントのすべてのパブリックプロパティがブロードキャストイベントに含まれます。Next, all that remains is to
listen for the event in our JavaScript application.
We can do this using Laravel
Echo[#client-side-installation]. First,
we'll use the private
method to
subscribe to the private channel. Then, we may use
the listen
method to listen for the
OrderShipmentStatusUpdated
event. By
default, all of the event's public properties will
be included on the broadcast event:
Echo.private(`orders.${orderId}`)
.listen('OrderShipmentStatusUpdated', (e) => {
console.log(e.order);
});
ブロードキャストイベントの定義Defining Broadcast Events
特定のイベントをブロードキャストする必要があることをLaravelに通知するには、イベントクラスにIlluminate\Contracts\Broadcasting\ShouldBroadcast
インターフェイスを実装する必要があります。このインターフェイスは、フレームワークで生成したすべてのイベントクラスに、最初からインポートされているため、どのイベントでも簡単に追加できます。To inform Laravel that a given
event should be broadcast, you must implement the
Illuminate\Contracts\Broadcasting\ShouldBroadcast
interface on the event class. This interface is
already imported into all event classes generated by
the framework so you may easily add it to any of
your events.
ShouldBroadcast
インターフェイスでは、broadcastOn
という単一のメソッドを実装する必要があります。broadcastOn
メソッドは、イベントがブロードキャストする必要があるチャンネルまたはチャンネルの配列を返す必要があります。チャンネルは、Channel
、PrivateChannel
、PresenceChannel
のインスタンスである必要があります。Channel
インスタンスは、すべてのユーザーがサブスクライブできるパブリックチャンネルを表し、PrivateChannels
とPresenceChannels
は、チャンネル認証を必要とするプライベートチャンネルを表します。The ShouldBroadcast
interface requires you to implement a single method:
broadcastOn
. The
broadcastOn
method should return a
channel or array of channels that the event should
broadcast on. The channels should be instances of
Channel
, PrivateChannel
,
or PresenceChannel
. Instances of
Channel
represent public channels that
any user may subscribe to, while
PrivateChannels
and
PresenceChannels
represent private
channels that require channel
authorization[#authorizing-channels]:
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class ServerCreated implements ShouldBroadcast
{
use SerializesModels;
/**
* 新しいイベントインスタンスの生成
*/
public function __construct(
public User $user,
) {}
/**
* イベントがブロードキャストするチャンネルを取得
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('user.'.$this->user->id),
];
}
}
ShouldBroadcast
インターフェイスを実装した後は、通常どおりイベントを発生させるだけです。イベントが発生すると、キューへジョブへ投入し、指定したブロードキャストドライバを使用し、イベントを自動的にブロードキャストします。After implementing the
ShouldBroadcast
interface, you only
need to fire the
event[/docs/{{version}}/events] as you
normally would. Once the event has been fired, a
queued job[/docs/{{version}}/queues] will
automatically broadcast the event using your
specified broadcast driver.
ブロードキャスト名Broadcast Name
デフォルトでは、Laravelはイベントのクラス名を使用してイベントをブロードキャストします。ただし、イベントでbroadcastAs
メソッドを定義することにより、ブロードキャスト名をカスタマイズできます。By default, Laravel will
broadcast the event using the event's class name.
However, you may customize the broadcast name by
defining a broadcastAs
method on the
event:
/**
* イベントのブロードキャスト名
*/
public function broadcastAs(): string
{
return 'server.created';
}
broadcastAs
メソッドを使用してブロードキャスト名をカスタマイズする場合は、リスナを先頭の.
文字で登録する必要があります。これにより、アプリケーションの名前空間をイベントの先頭に追加しないようにEchoに指示します。If you customize the broadcast
name using the broadcastAs
method, you
should make sure to register your listener with a
leading .
character. This will instruct
Echo to not prepend the application's namespace to
the event:
.listen('.server.created', function (e) {
....
});
ブロードキャストデータBroadcast Data
イベントをブロードキャストすると、そのすべてのpublic
プロパティが自動的にシリアライズされ、イベントのペイロードとしてブロードキャストされるため、JavaScriptアプリケーションからそのパブリックデータにアクセスできます。したがって、たとえば、イベントにEloquentモデルを含む単一のパブリック$user
プロパティがある場合、イベントのブロードキャストペイロードは次のようになります。When an event is broadcast, all
of its public
properties are
automatically serialized and broadcast as the
event's payload, allowing you to access any of its
public data from your JavaScript application. So,
for example, if your event has a single public
$user
property that contains an
Eloquent model, the event's broadcast payload would
be:
{
"user": {
"id": 1,
"name": "Patrick Stewart"
...
}
}
ただし、ブロードキャストペイロードをよりきめ細かく制御したい場合は、イベントにbroadcastWith
メソッドを追加できます。このメソッドは、ブロードキャストするデータの配列をイベントペイロードとして返す必要があります。However, if you wish to have more
fine-grained control over your broadcast payload,
you may add a broadcastWith
method to
your event. This method should return the array of
data that you wish to broadcast as the event
payload:
/**
* ブロードキャストするデータを取得
*
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return ['id' => $this->user->id];
}
ブロードキャストキューBroadcast Queue
デフォルトで各ブロードキャストイベントは、queue.php
設定ファイルで指定したデフォルトキュー接続のデフォルトキューへ配置されます。イベントクラスでconnection
プロパティとqueue
プロパティを定義することにより、ブロードキャスタが使用するキュー接続と名前をカスタマイズできます。By default, each broadcast event
is placed on the default queue for the default queue
connection specified in your queue.php
configuration file. You may customize the queue
connection and name used by the broadcaster by
defining connection
and
queue
properties on your event
class:
/**
* イベントをブロードキャストするときに使用するキュー接続の名前
*
* @var string
*/
public $connection = 'redis';
/**
* ブロードキャストジョブを投入するキュー名
*
* @var string
*/
public $queue = 'default';
あるいは、イベントにbroadcastQueue
メソッドを定義し、キュー名をカスタマイズできます。Alternatively, you may customize
the queue name by defining a
broadcastQueue
method on your
event:
/**
* ブロードキャストジョブを投入するキュー名
*/
public function broadcastQueue(): string
{
return 'default';
}
デフォルトのキュードライバではなく、sync
キューを使用してイベントをブロードキャストしたい場合は、ShouldBroadcast
の代わりにShouldBroadcastNow
インターフェイスを実装します。If you would like to broadcast
your event using the sync
queue instead
of the default queue driver, you can implement the
ShouldBroadcastNow
interface instead of
ShouldBroadcast
:
<?php
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class OrderShipmentStatusUpdated implements ShouldBroadcastNow
{
// ...
}
ブロードキャスト条件Broadcast Conditions
特定の条件が真である場合にのみイベントをブロードキャストしたい場合があります。イベントクラスにbroadcastWhen
メソッドを追加することで、こうした条件を定義できます。Sometimes you want to broadcast
your event only if a given condition is true. You
may define these conditions by adding a
broadcastWhen
method to your event
class:
/**
* このイベントをブロードキャストするかどうかを判定
*/
public function broadcastWhen(): bool
{
return $this->order->value > 100;
}
ブロードキャストとデータベーストランザクションBroadcasting and Database Transactions
ブロードキャストイベントがデータベーストランザクション内でディスパッチされると、データベーストランザクションがコミットされる前にキューによって処理される場合があります。これが起きると、データベーストランザクション中にモデルまたはデータベースレコードに加えた更新は、データベースにまだ反映されていない可能性があります。さらに、トランザクション内で作成されたモデルまたはデータベースレコードは、データベースに存在しない可能性があります。イベントがこれらのモデルに依存している場合、イベントをブロードキャストするジョブの処理時に予期しないエラーが発生する可能性があります。When broadcast events are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your event depends on these models, unexpected errors can occur when the job that broadcasts the event is processed.
キュー接続のafter_commit
設定オプションがfalse
に設定されている場合でも、イベントクラスでShouldDispatchAfterCommit
インターフェイスを実装することにより、開いているすべてのデータベーストランザクションがコミットされた後に特定のブロードキャストイベントをディスパッチする必要があることを示すことができます。If your queue connection's
after_commit
configuration option is
set to false
, you may still indicate
that a particular broadcast event should be
dispatched after all open database transactions have
been committed by implementing the
ShouldDispatchAfterCommit
interface on
the event class:
<?php
namespace App\Events;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Queue\SerializesModels;
class ServerCreated implements ShouldBroadcast, ShouldDispatchAfterCommit
{
use SerializesModels;
}
キュー投入済みジョブとデータベーストランザクションに関するドキュメントを確認してください。[!NOTE]
Note: こうした問題の回避方法の詳細は、
To learn more about working around these issues, please review the documentation regarding queued jobs and database transactions[/docs/{{version}}/queues#jobs-and-database-transactions].
チャンネルの認可Authorizing Channels
プライベートチャンネルでは、現在認証済みのユーザーが、実際にチャンネルをリッスンできることを認証する必要があります。これは、チャンネル名を指定してLaravelアプリケーションにHTTPリクエストを行い、ユーザーがそのチャンネルをリッスンできるかどうかをアプリケーション側が判断することで実現します。Laravel Echoを使用すると、プライベートチャンネルのサブスクリプションを承認するHTTPリクエストが自動的に行われます。Private channels require you to authorize that the currently authenticated user can actually listen on the channel. This is accomplished by making an HTTP request to your Laravel application with the channel name and allowing your application to determine if the user can listen on that channel. When using Laravel Echo[#client-side-installation], the HTTP request to authorize subscriptions to private channels will be made automatically.
ブロードキャストを有効になると、Laravelは認証リクエストを処理するため、/broadcasting/auth
ルートを自動的に登録します。/broadcasting/auth
ルートは自動的に、web
ミドルウェアグループへ配置しますWhen broadcasting is enabled,
Laravel automatically registers the
/broadcasting/auth
route to handle
authorization requests. The
/broadcasting/auth
route is
automatically placed within the web
middleware group.
認可コールバックの定義Defining Authorization Callbacks
次に、現在認証済みのユーザーが、指定チャンネルを視聴できるかどうかを実際に判断するロジックを定義する必要があります。これは、install:broadcasting
Artisanコマンドで作成したroutes/channels.php
ファイルで行います。このファイルでBroadcast::channel
メソッドを使用して、チャンネル認証コールバックを登録してください。Next, we need to define the logic
that will actually determine if the currently
authenticated user can listen to a given channel.
This is done in the routes/channels.php
file that was created by the
install:broadcasting
Artisan command.
In this file, you may use the
Broadcast::channel
method to register
channel authorization callbacks:
use App\Models\User;
Broadcast::channel('orders.{orderId}', function (User $user, int $orderId) {
return $user->id === Order::findOrNew($orderId)->user_id;
});
channel
メソッドは、チャンネルの名前と、ユーザーがチャンネルでのリッスンを許可されているかどうかを示すtrue
またはfalse
を返すコールバックの2つの引数を取ります。The channel
method
accepts two arguments: the name of the channel and a
callback which returns true
or
false
indicating whether the user is
authorized to listen on the channel.
すべての認可コールバックは、現在認証されているユーザーを最初の引数として受け取り、追加のワイルドカードパラメーターを後続の引数として受け取ります。この例では、{orderId}
プレースホルダーを使用して、チャンネル名の「ID」部分がワイルドカードであることを示しています。All authorization callbacks
receive the currently authenticated user as their
first argument and any additional wildcard
parameters as their subsequent arguments. In this
example, we are using the {orderId}
placeholder to indicate that the "ID"
portion of the channel name is a
wildcard.
channel:list
Artisanコマンドを使用すると、アプリケーションのブロードキャスト認可コールバックのリストを表示できます。You may view a list of your
application's broadcast authorization callbacks
using the channel:list
Artisan
command:
php artisan channel:list
認可コールバックモデルのバインドAuthorization Callback Model Binding
HTTPルートと同様に、チャンネルルートも暗黙的および明示的なルートモデルバインディングを利用できます。たとえば、文字列または数値の注文IDを受け取る代わりに、実際のOrder
モデルインスタンスを要求できます。Just like HTTP routes, channel
routes may also take advantage of implicit and
explicit route model
binding[/docs/{{version}}/routing#route-model-binding].
For example, instead of receiving a string or
numeric order ID, you may request an actual
Order
model instance:
use App\Models\Order;
use App\Models\User;
Broadcast::channel('orders.{order}', function (User $user, Order $order) {
return $user->id === $order->user_id;
});
暗黙的モデルバインディングスコープをサポートしていません。ただし、ほとんどのチャンネルは単一のモデルの一意の主キーに基づいてスコープを設定できるため、これが問題になることはめったにありません。[!WARNING]
Warning! HTTPルートモデルバインディングとは異なり、チャンネルモデルバインディングは自動
Unlike HTTP route model binding, channel model binding does not support automatic implicit model binding scoping[/docs/{{version}}/routing#implicit-model-binding-scoping]. However, this is rarely a problem because most channels can be scoped based on a single model's unique, primary key.
認可コールバック認証Authorization Callback Authentication
プライベートおよびプレゼンスブロードキャストチャンネルは、アプリケーションのデフォルトの認証ガードを介して現在のユーザーを認証します。ユーザーが認証されていない場合、チャンネル認可は自動的に拒否され、認可コールバックは実行されません。ただし、必要に応じて、受信リクエストを認証する複数の必要なカスタムガードを割り当てることができます。Private and presence broadcast channels authenticate the current user via your application's default authentication guard. If the user is not authenticated, channel authorization is automatically denied and the authorization callback is never executed. However, you may assign multiple, custom guards that should authenticate the incoming request if necessary:
Broadcast::channel('channel', function () {
// ...
}, ['guards' => ['web', 'admin']]);
チャンネルクラスの定義Defining Channel Classes
アプリケーションが多くの異なるチャンネルを使用している場合、routes/channels.php
ファイルがかさばる可能性が起きます。そのため、クロージャを使用してチャンネルを認可する代わりに、チャンネルクラスを使用できます。チャンネルクラスを生成するには、make:channel
Artisanコマンドを使用します。このコマンドは、新しいチャンネルクラスをApp/Broadcasting
ディレクトリに配置します。If your application is consuming
many different channels, your
routes/channels.php
file could become
bulky. So, instead of using closures to authorize
channels, you may use channel classes. To generate a
channel class, use the make:channel
Artisan command. This command will place a new
channel class in the App/Broadcasting
directory.
php artisan make:channel OrderChannel
次に、チャンネルをroutes/channels.php
ファイルに登録します。Next, register your channel in
your routes/channels.php
file:
use App\Broadcasting\OrderChannel;
Broadcast::channel('orders.{order}', OrderChannel::class);
最後に、チャンネルの認可ロジックをチャンネルクラスのjoin
メソッドに配置できます。このjoin
メソッドは、チャンネル認可クロージャに通常配置するのと同じロジックを格納します。チャンネルモデルバインディングを利用することもできます。Finally, you may place the
authorization logic for your channel in the channel
class' join
method. This
join
method will house the same logic
you would have typically placed in your channel
authorization closure. You may also take advantage
of channel model binding:
<?php
namespace App\Broadcasting;
use App\Models\Order;
use App\Models\User;
class OrderChannel
{
/**
* 新しいチャンネルインスタンスの生成
*/
public function __construct()
{
// ...
}
/**
* チャンネルへのユーザーのアクセスを認可
*/
public function join(User $user, Order $order): array|bool
{
return $user->id === $order->user_id;
}
}
サービスコンテナによって自動的に依存解決されます。そのため、コンストラクターでチャンネルに必要な依存関係をタイプヒントすることができます。[!NOTE]
Note: Laravelの他の多くのクラスと同様に、チャンネルクラスは
Like many other classes in Laravel, channel classes will automatically be resolved by the service container[/docs/{{version}}/container]. So, you may type-hint any dependencies required by your channel in its constructor.
ブロードキャストイベントBroadcasting Events
イベントを定義し、ShouldBroadcast
インターフェイスでマークを付けたら、イベントのディスパッチメソッドを使用してイベントを発生させるだけです。イベントディスパッチャは、イベントがShouldBroadcast
インターフェイスでマークされていることに気付き、ブロードキャストのためにイベントをキューに入れます。Once you have defined an event
and marked it with the ShouldBroadcast
interface, you only need to fire the event using the
event's dispatch method. The event dispatcher will
notice that the event is marked with the
ShouldBroadcast
interface and will
queue the event for broadcasting:
use App\Events\OrderShipmentStatusUpdated;
OrderShipmentStatusUpdated::dispatch($order);
他の人だけへの送信Only to Others
イベントブロードキャストを利用するアプリケーションを構築する場合、特定のチャンネルで現在のユーザーを除く、すべてのサブスクライバにイベントをブロードキャストする必要が起きる場合があります。これは、broadcast
ヘルパとtoOthers
メソッドを使用して実行できます。When building an application that
utilizes event broadcasting, you may occasionally
need to broadcast an event to all subscribers to a
given channel except for the current user. You may
accomplish this using the broadcast
helper and the toOthers
method:
use App\Events\OrderShipmentStatusUpdated;
broadcast(new OrderShipmentStatusUpdated($update))->toOthers();
toOthers
メソッドをいつ使用したらよいかをよりよく理解するために、ユーザーがタスク名を入力して新しいタスクを作成できるタスクリストアプリケーションを想像してみましょう。タスクを作成するために、アプリケーションは、タスクの作成をブロードキャストし、新しいタスクのJSON表現を返す/task
URLにリクエストを送信する場合があります。JavaScriptアプリケーションがエンドポイントから応答を受信すると、次のように新しいタスクをタスクリストに直接挿入する場合があるでしょう。To better understand when you may
want to use the toOthers
method, let's
imagine a task list application where a user may
create a new task by entering a task name. To create
a task, your application might make a request to a
/task
URL which broadcasts the task's
creation and returns a JSON representation of the
new task. When your JavaScript application receives
the response from the end-point, it might directly
insert the new task into its task list like
so:
axios.post('/task', task)
.then((response) => {
this.tasks.push(response.data);
});
ただし、タスクの作成もブロードキャストすることを忘れないでください。JavaScriptアプリケーションがタスクリストにタスクを追加するためにこのイベントもリッスンしている場合、リストには重複するタスクが発生します。1つはエンドポイントからのもので、もう1つはブロードキャストからのものです。これを解決するには、toOthers
メソッドを使用して、現在のユーザーにはイベントをブロードキャストしないようにブロードキャスタへ指示します。However, remember that we also
broadcast the task's creation. If your JavaScript
application is also listening for this event in
order to add tasks to the task list, you will have
duplicate tasks in your list: one from the end-point
and one from the broadcast. You may solve this by
using the toOthers
method to instruct
the broadcaster to not broadcast the event to the
current user.
Warning!
toOthers
メソッドを呼び出すには、イベントでIlluminate\Broadcasting\InteractsWithSockets
トレイトをuseする必要があります。[!WARNING]
Your event must use theIlluminate\Broadcasting\InteractsWithSockets
trait in order to call thetoOthers
method.
設定Configuration
Laravel Echoインスタンスを初期化すると、ソケットIDが接続に割り当てられます。グローバルAxiosインスタンスを使用してJavaScriptアプリケーションからHTTPリクエストを作成している場合、ソケットIDはすべての送信リクエストにX-Socket-ID
ヘッダとして自動的に添付されます。次に、toOthers
メソッドを呼び出すと、LaravelはヘッダからソケットIDを抽出し、そのソケットIDを持つ接続にブロードキャストしないようにブロードキャスタに指示します。When you initialize a Laravel
Echo instance, a socket ID is assigned to the
connection. If you are using a global
Axios[https://github.com/mzabriskie/axios]
instance to make HTTP requests from your JavaScript
application, the socket ID will automatically be
attached to every outgoing request as an
X-Socket-ID
header. Then, when you call
the toOthers
method, Laravel will
extract the socket ID from the header and instruct
the broadcaster to not broadcast to any connections
with that socket ID.
グローバルAxiosインスタンスを使用しない場合は、すべての送信リクエストでX-Socket-ID
ヘッダを送信するようにJavaScriptアプリケーションを手作業で設定する必要があります。Echo.socketId
メソッドを使用してソケットIDを取得できます。If you are not using a global
Axios instance, you will need to manually configure
your JavaScript application to send the
X-Socket-ID
header with all outgoing
requests. You may retrieve the socket ID using the
Echo.socketId
method:
var socketId = Echo.socketId();
コネクションのカスタマイズCustomizing the Connection
アプリケーションが複数のブロードキャスト接続とやりとりしており、デフォルト以外のブロードキャスタを使いイベントをブロードキャストしたい場合は、via
メソッドを使ってどの接続へイベントをプッシュするか指定できます。If your application interacts
with multiple broadcast connections and you want to
broadcast an event using a broadcaster other than
your default, you may specify which connection to
push an event to using the via
method:
use App\Events\OrderShipmentStatusUpdated;
broadcast(new OrderShipmentStatusUpdated($update))->via('pusher');
もしくは、イベントのコンストラクタで broadcastVia
メソッドを呼び出して、イベントのブロードキャスト接続を指定することもできます。ただし、そのときは、イベントクラスで確実にInteractsWithBroadcasting
トレイトをuseしてください。Alternatively, you may specify
the event's broadcast connection by calling the
broadcastVia
method within the event's
constructor. However, before doing so, you should
ensure that the event class uses the
InteractsWithBroadcasting
trait:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithBroadcasting;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
class OrderShipmentStatusUpdated implements ShouldBroadcast
{
use InteractsWithBroadcasting;
/**
* 新しいイベントインスタンスの生成
*/
public function __construct()
{
$this->broadcastVia('pusher');
}
}
ブロードキャストの受け取りReceiving Broadcasts
イベントのリッスンListening for Events
Laravel
Echoをインストールしてインスタンス化すると、Laravelアプリケーションからブロードキャストされるイベントをリッスンする準備が整います。まず、channel
メソッドを使用してチャンネルのインスタンスを取得し、次にlisten
メソッドを呼び出して指定されたイベントをリッスンします。Once you have installed and
instantiated Laravel
Echo[#client-side-installation], you are
ready to start listening for events that are
broadcast from your Laravel application. First, use
the channel
method to retrieve an
instance of a channel, then call the
listen
method to listen for a specified
event:
Echo.channel(`orders.${this.order.id}`)
.listen('OrderShipmentStatusUpdated', (e) => {
console.log(e.order.name);
});
プライベートチャンネルでイベントをリッスンする場合は、代わりにprivate
メソッドを使用してください。listen
メソッドへの呼び出しをチェーンして、単一のチャンネルで複数のイベントをリッスンすることができます。If you would like to listen for
events on a private channel, use the
private
method instead. You may
continue to chain calls to the listen
method to listen for multiple events on a single
channel:
Echo.private(`orders.${this.order.id}`)
.listen(/* ... */)
.listen(/* ... */)
.listen(/* ... */);
Stop Listening for EventsStop Listening for Events
チャンネルから離れることなく特定のイベントのリッスンを停止したい場合は、stopListening
メソッドを使用します。If you would like to stop
listening to a given event without leaving the
channel[#leaving-a-channel], you may use the
stopListening
method:
Echo.private(`orders.${this.order.id}`)
.stopListening('OrderShipmentStatusUpdated')
Leaving a ChannelLeaving a Channel
チャンネルを離れるには、EchoインスタンスでleaveChannel
メソッドを呼び出してください。To leave a channel, you may call
the leaveChannel
method on your Echo
instance:
Echo.leaveChannel(`orders.${this.order.id}`);
チャンネルとそれに関連するプライベートチャンネルおよびプレゼンスチャンネルを離れたい場合は、leave
メソッドを呼び出してください。If you would like to leave a
channel and also its associated private and presence
channels, you may call the leave
method:
Echo.leave(`orders.${this.order.id}`);
名前空間Namespaces
上記の例で、イベントクラスに完全なApp\Events
名前空間を指定していないことに気付いたかもしれません。これは、EchoがイベントがApp\Events
名前空間にあると自動的に想定するためです。ただし、namespace
設定オプションを渡すことにより、Echoをインスタンス化するときにルート名前空間を設定できます。You may have noticed in the
examples above that we did not specify the full
App\Events
namespace for the event
classes. This is because Echo will automatically
assume the events are located in the
App\Events
namespace. However, you may
configure the root namespace when you instantiate
Echo by passing a namespace
configuration option:
window.Echo = new Echo({
broadcaster: 'pusher',
// ...
namespace: 'App.Other.Namespace'
});
または、Echoを使用してサブスクライブするときに、イベントクラスの前に.
を付けることもできます。これにより、常に完全修飾クラス名を指定できます。Alternatively, you may prefix
event classes with a .
when subscribing
to them using Echo. This will allow you to always
specify the fully-qualified class name:
Echo.channel('orders')
.listen('.Namespace\\Event\\Class', (e) => {
// ...
});
プレゼンスチャンネルPresence Channels
プレゼンスチャンネルは、プライベートチャンネルのセキュリティを基盤とし、チャンネルにサブスクライブしているユーザーを認識するという追加機能を付け加えます。これにより、別のユーザーが同じページを表示しているときにユーザーに通知したり、チャットルームの住民を一覧表示したりするなど、強力なコラボレーションアプリケーション機能を簡単に構築できます。Presence channels build on the security of private channels while exposing the additional feature of awareness of who is subscribed to the channel. This makes it easy to build powerful, collaborative application features such as notifying users when another user is viewing the same page or listing the inhabitants of a chat room.
プレゼンスチャンネルの認可Authorizing Presence Channels
すべてのプレゼンスチャンネルもプライベートチャンネルです。したがって、ユーザーはアクセス許可を持つ必要があります。ただし、プレゼンスチャンネルの認可コールバックを定義する場合、ユーザーがチャンネルへの参加を認可されている場合に、true
を返しません。代わりに、ユーザーに関するデータの配列を返す必要があります。All presence channels are also
private channels; therefore, users must be
authorized to access
them[#authorizing-channels]. However, when
defining authorization callbacks for presence
channels, you will not return true
if
the user is authorized to join the channel. Instead,
you should return an array of data about the
user.
認可コールバックが返すデータは、JavaScriptアプリケーションのプレゼンスチャンネルイベントリスナが利用できるようになります。ユーザーがプレゼンスチャンネルへの参加を許可されていない場合は、false
またはnull
を返す必要があります。The data returned by the
authorization callback will be made available to the
presence channel event listeners in your JavaScript
application. If the user is not authorized to join
the presence channel, you should return
false
or null
:
use App\Models\User;
Broadcast::channel('chat.{roomId}', function (User $user, int $roomId) {
if ($user->canJoinRoom($roomId)) {
return ['id' => $user->id, 'name' => $user->name];
}
});
プレゼンスチャンネルへの接続Joining Presence Channels
プレゼンスチャンネルに参加するには、Echoのjoin
メソッドを使用できます。join
メソッドはPresenceChannel
実装を返します。これは、listen
メソッドを公開するとともに、here
、joining
、およびleaving
イベントをサブスクライブできるようにします。To join a presence channel, you
may use Echo's join
method. The
join
method will return a
PresenceChannel
implementation which,
along with exposing the listen
method,
allows you to subscribe to the here
,
joining
, and leaving
events.
Echo.join(`chat.${roomId}`)
.here((users) => {
// ...
})
.joining((user) => {
console.log(user.name);
})
.leaving((user) => {
console.log(user.name);
})
.error((error) => {
console.error(error);
});
here
コールバックは、チャンネルへ正常に参加するとすぐに実行され、現在チャンネルにサブスクライブしている他のすべてのユーザーのユーザー情報を含む配列を受け取ります。joining
メソッドは、新しいユーザーがチャンネルに参加したときに実行され、leaving
メソッドは、ユーザーがチャンネルを離れたときに実行されます。error
メソッドは、認証エンドポイントが200以外のHTTPステータスコードを返した場合や、返されたJSONの解析で問題があった場合に実行されます。The here
callback
will be executed immediately once the channel is
joined successfully, and will receive an array
containing the user information for all of the other
users currently subscribed to the channel. The
joining
method will be executed when a
new user joins a channel, while the
leaving
method will be executed when a
user leaves the channel. The error
method will be executed when the authentication
endpoint returns an HTTP status code other than 200
or if there is a problem parsing the returned
JSON.
プレゼンスチャンネルへのブロードキャストBroadcasting to Presence Channels
プレゼンスチャンネルは、パブリックチャンネルまたはプライベートチャンネルと同じようにイベントを受信できます。チャットルームの例を使用して、NewMessage
イベントをルームのプレゼンスチャンネルにブロードキャストしたいとしましょう。そのために、イベントのbroadcastOn
メソッドからPresenceChannel
のインスタンスを返します。Presence channels may receive
events just like public or private channels. Using
the example of a chatroom, we may want to broadcast
NewMessage
events to the room's
presence channel. To do so, we'll return an instance
of PresenceChannel
from the event's
broadcastOn
method:
/**
* イベントをブロードキャストするチャンネルを取得
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
return [
new PresenceChannel('chat.'.$this->message->room_id),
];
}
他のイベントと同様に、broadcast
ヘルパとtoOthers
メソッドを使用して、現在のユーザーをブロードキャストの受信から除外できます。As with other events, you may use
the broadcast
helper and the
toOthers
method to exclude the current
user from receiving the broadcast:
broadcast(new NewMessage($message));
broadcast(new NewMessage($message))->toOthers();
他の典型的なタイプのイベントと同様に、Echoのlisten
メソッドを使用してプレゼンスチャンネルに送信されたイベントをリッスンできます。As typical of other types of
events, you may listen for events sent to presence
channels using Echo's listen
method:
Echo.join(`chat.${roomId}`)
.here(/* ... */)
.joining(/* ... */)
.leaving(/* ... */)
.listen('NewMessage', (e) => {
// ...
});
モデルブロードキャストModel Broadcasting
[!WARNING]
Warning! モデルブロードキャストに関する以降のドキュメントを読む前に、Laravelのモデルブロードキャストサービスの一般的なコンセプトや、ブロードキャストイベントを手作業で作成したり、リッスンしたりする方法に精通しておくことをおすすめします。
Before reading the following documentation about model broadcasting, we recommend you become familiar with the general concepts of Laravel's model broadcasting services as well as how to manually create and listen to broadcast events.
アプリケーションのEloquentモデルが作成、更新、または削除されたときにイベントをブロードキャストするのは一般的です。もちろん、これは自前でEloquentモデルの状態変化を表すカスタムイベントを定義し、それらのイベントをShouldBroadcast
インターフェイスでマークすることで簡単に実現できます。It is common to broadcast events
when your application's Eloquent
models[/docs/{{version}}/eloquent] are
created, updated, or deleted. Of course, this can
easily be accomplished by manually defining
custom events for Eloquent model state
changes[/docs/{{version}}/eloquent#events]
and marking those events with the
ShouldBroadcast
interface.
しかし、こうしたイベントをアプリケーション内で他の目的に使用しない場合、イベントをブロードキャストするためだけにイベントクラスを作成するのは面倒なことです。そのためLaravelは指定があれば、Eloquentモデルの状態変化を自動的にブロードキャストします。However, if you are not using these events for any other purposes in your application, it can be cumbersome to create event classes for the sole purpose of broadcasting them. To remedy this, Laravel allows you to indicate that an Eloquent model should automatically broadcast its state changes.
まず始めに、Eloquentモデルで、Illuminate\Database\BroadcastsEvents
トレイトを使用する必要があります。さらに、そのモデルでbroadcastOn
メソッドを定義する必要があります。このメソッドは、モデルイベントをブロードキャストするチャンネルの配列を返します。To get started, your Eloquent
model should use the
Illuminate\Database\Eloquent\BroadcastsEvents
trait. In addition, the model should define a
broadcastOn
method, which will return
an array of channels that the model's events should
broadcast on:
<?php
namespace App\Models;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Database\Eloquent\BroadcastsEvents;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
use BroadcastsEvents, HasFactory;
/**
* ポストが属するユーザーの取得
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* モデルイベントをブロードキャストするチャンネルを取得
*
* @return array<int, \Illuminate\Broadcasting\Channel|\Illuminate\Database\Eloquent\Model>
*/
public function broadcastOn(string $event): array
{
return [$this, $this->user];
}
}
モデルでこの特性を使い、そしてブロードキャスト・チャンネルを定義したら、モデルインスタンスの作成、更新、削除、ソフトデリートと復元のとき、自動的にイベントのブロードキャストが開始されます。Once your model includes this trait and defines its broadcast channels, it will begin automatically broadcasting events when a model instance is created, updated, deleted, trashed, or restored.
さらに、broadcastOn
メソッドが文字列の$event
引数を受け取っていることにお気づきでしょう。この引数には、モデルで発生したイベントの種類が含まれており、created
、updated
、deleted
、trashed
、restored
のいずれかの値を持ちます。この変数の値を調べることで、必要であれば、特定のイベントに対しモデルをどのチャンネルへブロードキャストするかを判定できます。In addition, you may have noticed
that the broadcastOn
method receives a
string $event
argument. This argument
contains the type of event that has occurred on the
model and will have a value of created
,
updated
, deleted
,
trashed
, or restored
. By
inspecting the value of this variable, you may
determine which channels (if any) the model should
broadcast to for a particular event:
/**
* モデルイベントをブロードキャストするチャンネルを取得
*
* @return array<string, array<int, \Illuminate\Broadcasting\Channel|\Illuminate\Database\Eloquent\Model>>
*/
public function broadcastOn(string $event): array
{
return match ($event) {
'deleted' => [],
default => [$this, $this->user],
};
}
モデルブロードキャストのイベント生成のカスタマイズCustomizing Model Broadcasting Event Creation
時には、Laravelのモデルブロードキャスティングイベントの作成方法をカスタマイズしたい場合も起きるでしょう。それには、EloquentモデルにnewBroadcastableEvent
メソッドを定義してください。このメソッドは、Illuminate\Database\Eloquent\BroadcastableModelEventOccurred
インスタンスを返す必要があります。Occasionally, you may wish to
customize how Laravel creates the underlying model
broadcasting event. You may accomplish this by
defining a newBroadcastableEvent
method
on your Eloquent model. This method should return an
Illuminate\Database\Eloquent\BroadcastableModelEventOccurred
instance:
use Illuminate\Database\Eloquent\BroadcastableModelEventOccurred;
/**
* このモデルのための新しいブロードキャストモデルイベントを作成
*/
protected function newBroadcastableEvent(string $event): BroadcastableModelEventOccurred
{
return (new BroadcastableModelEventOccurred(
$this, $event
))->dontBroadcastToCurrentUser();
}
モデルブロードキャスト規約Model Broadcasting Conventions
チャンネル規約Channel Conventions
お気づきかもしれませんが、上記のモデル例のbroadcastOn
メソッドは、Channel
インスタンスを返していません。代わりにEloquentモデルを直接返しています。モデルのbroadcastOn
メソッドが、Eloquentモデルインスタンスを返す場合(または、メソッドが返す配列に含まれている場合)、Laravelはモデルのクラス名と主キー識別子をチャンネル名とする、モデルのプライベートチャンネルインスタンスを自動的にインスタンス化します。As you may have noticed, the
broadcastOn
method in the model example
above did not return Channel
instances.
Instead, Eloquent models were returned directly. If
an Eloquent model instance is returned by your
model's broadcastOn
method (or is
contained in an array returned by the method),
Laravel will automatically instantiate a private
channel instance for the model using the model's
class name and primary key identifier as the channel
name.
つまり、id
が1
のApp\Models\User
モデルは、App.Models.User.1
という名前のIlluminate\Broadcasting\PrivateChannel
インスタンスへ変換されるわけです。もちろん、モデルのbroadcastOn
メソッドから、Eloquentモデルインスタンスを返すことに加え、モデルのチャンネル名を完全にコントロールするため、完全なChannel
インスタンスを返すこともできます。So, an
App\Models\User
model with an
id
of 1
would be converted
into an
Illuminate\Broadcasting\PrivateChannel
instance with a name of
App.Models.User.1
. Of course, in
addition to returning Eloquent model instances from
your model's broadcastOn
method, you
may return complete Channel
instances
in order to have full control over the model's
channel names:
use Illuminate\Broadcasting\PrivateChannel;
/**
* モデルイベントをブロードキャストするチャンネルを取得
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(string $event): array
{
return [
new PrivateChannel('user.'.$this->id)
];
}
モデルのbroadcastOn
メソッドからチャンネルのインスタンスを明示的に返す場合は、チャンネルのコンストラクタにEloquentモデルのインスタンスを渡すことができます。そうすると、Laravelは上述のモデルチャンネルの規約を使って、Eloquentモデルをチャンネル名の文字列に変換します。If you plan to explicitly return
a channel instance from your model's
broadcastOn
method, you may pass an
Eloquent model instance to the channel's
constructor. When doing so, Laravel will use the
model channel conventions discussed above to convert
the Eloquent model into a channel name
string:
return [new Channel($this->user)];
モデルのチャンネル名を決定する必要がある場合は、モデルインスタンスでbroadcastChannel
メソッドを呼び出してください。たとえば、1
のid
を持つApp\Models\User
モデルに対し、このメソッドは文字列App.Models.User.1
を返します。If you need to determine the
channel name of a model, you may call the
broadcastChannel
method on any model
instance. For example, this method returns the
string App.Models.User.1
for an
App\Models\User
model with an
id
of 1
:
$user->broadcastChannel()
イベント規約Event Conventions
モデルのブロードキャストイベントは、アプリケーションのApp\Events
ディレクトリ内の「実際の」イベントとは関連していないので、規約に基づいて名前とペイロードが割り当てられます。Laravelの規約では、モデルのクラス名(名前空間を含まない)と、ブロードキャストのきっかけとなったモデルイベントの名前を使って、イベントをブロードキャストします。Since model broadcast events are
not associated with an "actual" event
within your application's App\Events
directory, they are assigned a name and a payload
based on conventions. Laravel's convention is to
broadcast the event using the class name of the
model (not including the namespace) and the name of
the model event that triggered the
broadcast.
ですから、例えば、App\Models\Post
モデルの更新は、以下のペイロードを持つPostUpdated
として、クライアントサイドのアプリケーションにイベントをブロードキャストします。So, for example, an update to the
App\Models\Post
model would broadcast
an event to your client-side application as
PostUpdated
with the following
payload:
{
"model": {
"id": 1,
"title": "My first post"
...
},
...
"socket": "someSocketId",
}
App\Models\User
モデルが削除されると、UserDeleted
という名前のイベントをブロードキャストします。The deletion of the
App\Models\User
model would broadcast
an event named UserDeleted
.
必要であれば、モデルに broadcastAs
と
broadcastWith
メソッドを追加することで、カスタムのブロードキャスト名とペイロードを定義することができます。これらのメソッドは、発生しているモデルのイベント/操作の名前を受け取るので、モデルの操作ごとにイベントの名前やペイロードをカスタマイズできます。もし、broadcastAs
メソッドからnull
が返された場合、Laravelはイベントをブロードキャストする際に、上記で説明したモデルのブロードキャストイベント名の規約を使用します。If you would like, you may define
a custom broadcast name and payload by adding a
broadcastAs
and
broadcastWith
method to your model.
These methods receive the name of the model event /
operation that is occurring, allowing you to
customize the event's name and payload for each
model operation. If null
is returned
from the broadcastAs
method, Laravel
will use the model broadcasting event name
conventions discussed above when broadcasting the
event:
/**
* モデルイベントのブロードキャスト名
*/
public function broadcastAs(string $event): string|null
{
return match ($event) {
'created' => 'post.created',
default => null,
};
}
/**
* モデルのブロードキャストのデータ取得
*
* @return array<string, mixed>
*/
public function broadcastWith(string $event): array
{
return match ($event) {
'created' => ['title' => $this->title],
default => ['model' => $this],
};
}
モデルブロードキャストのリッスンListening for Model Broadcasts
モデルへBroadcastsEvents
トレイトを追加し、モデルのbroadcastOn
メソッドを定義したら、クライアントサイドのアプリケーションで、ブロードキャストしたモデルイベントをリッスンする準備ができました。始める前に、イベントのリッスンの完全なドキュメントを参照しておくとよいでしょう。Once you have added the
BroadcastsEvents
trait to your model
and defined your model's broadcastOn
method, you are ready to start listening for
broadcasted model events within your client-side
application. Before getting started, you may wish to
consult the complete documentation on listening
for
events[#listening-for-events].
まず、private
メソッドでチャンネルのインスタンスを取得し、それからlisten
メソッドを呼び出して、指定したイベントをリッスンします。通常、private
メソッドへ指定するチャンネル名は、Laravelのモデルブロードキャスト規約に対応していなければなりません。First, use the
private
method to retrieve an instance
of a channel, then call the listen
method to listen for a specified event. Typically,
the channel name given to the private
method should correspond to Laravel's model
broadcasting
conventions[#model-broadcasting-conventions].
チャンネルインスタンスを取得したら、listen
メソッドを使って特定のイベントをリッスンします。モデルのブロードキャストイベントは、アプリケーションのApp\Events
ディレクトリにある「実際の」イベントと関連付けられていないため、イベント名の前に.
を付けて、特定の名前空間に属していないことを示す必要があります。各モデルブロードキャストイベントは、そのモデルのブロードキャスト可能なプロパティをすべて含むmodel
プロパティを持ちます。Once you have obtained a channel
instance, you may use the listen
method
to listen for a particular event. Since model
broadcast events are not associated with an
"actual" event within your application's
App\Events
directory, the event
name[#model-broadcasting-event-conventions]
must be prefixed with a .
to indicate
it does not belong to a particular namespace. Each
model broadcast event has a model
property which contains all of the broadcastable
properties of the model:
Echo.private(`App.Models.User.${this.user.id}`)
.listen('.PostUpdated', (e) => {
console.log(e.model);
});
クライアントイベントClient Events
Pusherチャンネルを使用する場合は、クライアントイベントを送信するためにアプリケーションダッシュボードの"App Settings"セクションの"Client Events"オプションを有効にする必要があります。[!NOTE]
Note:
When using Pusher Channels[https://pusher.com/channels], you must enable the "Client Events" option in the "App Settings" section of your application dashboard[https://dashboard.pusher.com/] in order to send client events.
Laravelアプリケーションにまったくアクセスせずに、接続済みの他のクライアントにイベントをブロードキャストしたい場合があります。これは、別のユーザーが特定の画面でメッセージを入力していることをアプリケーションのユーザーに警告する「入力」通知などに特に役立ちます。Sometimes you may wish to broadcast an event to other connected clients without hitting your Laravel application at all. This can be particularly useful for things like "typing" notifications, where you want to alert users of your application that another user is typing a message on a given screen.
クライアントイベントをブロードキャストするには、Echoのwhisper
メソッドを使用できます。To broadcast client events, you
may use Echo's whisper
method:
Echo.private(`chat.${roomId}`)
.whisper('typing', {
name: this.user.name
});
クライアントイベントをリッスンするには、listenForWhisper
メソッドを使用します。To listen for client events, you
may use the listenForWhisper
method:
Echo.private(`chat.${roomId}`)
.listenForWhisper('typing', (e) => {
console.log(e.name);
});
通知Notifications
イベントブロードキャストを通知と組み合わせることで、JavaScriptアプリケーションは、ページを更新せず発生した新しい通知を受け取ることができます。実現する前に、ブロードキャスト通知チャンネルの使用に関するドキュメントを必ずお読みください。By pairing event broadcasting with notifications[/docs/{{version}}/notifications], your JavaScript application may receive new notifications as they occur without needing to refresh the page. Before getting started, be sure to read over the documentation on using the broadcast notification channel[/docs/{{version}}/notifications#broadcast-notifications].
ブロードキャストチャンネルを使用するように通知を設定すると、Echoのnotification
メソッドを使用してブロードキャストイベントをリッスンできます。チャンネル名は、通知を受信するエンティティのクラス名と一致する必要があることに注意してください。Once you have configured a
notification to use the broadcast channel, you may
listen for the broadcast events using Echo's
notification
method. Remember, the
channel name should match the class name of the
entity receiving the notifications:
Echo.private(`App.Models.User.${userId}`)
.notification((notification) => {
console.log(notification.type);
});
この例ではbroadcast
チャネル経由でApp\Models\User
インスタンスへ送信されたすべての通知をコールバックが受信しています。App.Models.User.{id}
チャネルのチャネル認可コールバックは、アプリケーションのroutes/channels.php
ファイルに含まれます。In this example, all
notifications sent to App\Models\User
instances via the broadcast
channel
would be received by the callback. A channel
authorization callback for the
App.Models.User.{id}
channel is
included in your application's
routes/channels.php
file.