Readouble

Laravel 10.x ブロードキャスト

イントロダクション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

By default, Laravel includes three server-side broadcasting drivers for you to choose from: Laravel Reverb, Pusher Channels, and 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].

lightbulb Note: イベントブロードキャストに取り掛かる前に、イベントとリスナに関するLaravelのドキュメントをしっかりと読んでください。[!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設定ファイルに保存します。Laravelは、すぐに使用できるブロードキャストドライバをいくつかサポートしています。PusherチャンネルRedis、およびローカルでの開発とデバッグ用のlogドライバです。さらに、テスト中にブロードキャストを完全に無効にできるnullドライバも用意しています。これら各ドライバの設定例は、config/broadcasting.php設定ファイルにあります。All of your application's event broadcasting configuration is stored in the config/broadcasting.php configuration file. Laravel supports several broadcast drivers out of the box: Pusher Channels[https://pusher.com/channels], Redis[/docs/{{version}}/redis], and a log driver for local development and debugging. Additionally, a null driver is included which allows you to totally disable broadcasting during testing. A configuration example is included for each of these drivers in the config/broadcasting.php configuration file.

ブロードキャストサービスプロバイダBroadcast Service Provider

イベントをブロードキャストする前に、まずApp\Providers\BroadcastServiceProviderを登録する必要があります。新しいLaravelアプリケーションでは、config/app.php設定ファイルのproviders配列で、このプロバイダをアンコメントするだけです。このBroadcastServiceProviderには、ブロードキャスト認可ルートとコールバックを登録するために必要なコードが含まれています。Before broadcasting any events, you will first need to register the App\Providers\BroadcastServiceProvider. In new Laravel applications, you only need to uncomment this provider in the providers array of your config/app.php configuration file. This BroadcastServiceProvider contains the code necessary to register the broadcast authorization routes and callbacks.

キュー設定Queue Configuration

また、キューワーカを設定して実行する必要があります。すべてのイベントブロードキャストはジョブをキュー投入し実行されるため、アプリケーションの応答時間は、ブロードキャストするイベントによる深刻な影響を受けません。You will also need to 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

ReverbはComposerパッケージマネージャを使い、インストールしてください。Reverbは現在ベータ版のため、明示的にベータ版をインストールする必要があります。You may install Reverb 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, update your applications's broadcasting configuration, and add Reverb's required environment variables:

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チャンネルの利用資格情報を設定する必要があります。Pusherチャンネル設定の例は予めこのファイルに含まれているため、キー、シークレット、およびアプリケーションIDを簡単に指定できます。通常、これらの値は、PUSHER_APP_KEYPUSHER_APP_SECRETPUSHER_APP_ID環境変数を介して設定する必要があります。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, these values should be set via the PUSHER_APP_KEY, PUSHER_APP_SECRET, and PUSHER_APP_ID environment variables[/docs/{{version}}/configuration#environment-configuration]:

PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
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ファイルでブロードキャストドライバをpusherに変更する必要があります。Next, you will need to change your broadcast driver to pusher in your .env file:

BROADCAST_DRIVER=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.

オープンソースによるPusherの代替Open Source Pusher Alternatives

soketiは、Laravel用のPusher互換WebSocketサーバを提供しており、商用WebSocketプロバイダーを使わずにLaravelブロードキャストのフルパワーを活用できます。ブロードキャスト用のオープンソースパッケージのインストールと使用の詳細については、オープンソースの代替のドキュメントを参照してください。soketi[https://docs.soketi.app/] provides a Pusher compatible WebSocket server for Laravel, allowing you to leverage the full power of Laravel broadcasting without a commercial WebSocket provider. For more information on installing and using open source packages for broadcasting, please consult our documentation on open source alternatives[#open-source-alternatives].

AblyAbly

lightbulb Note: 以下のドキュメントでは、Ablyを「Pusher互換」モードで使用する方法について説明していきます。しかし、Ablyチームは、Ablyが提供するユニークな機能を活用できるブロードキャスターとEchoクライアントを推奨し、保守しています。Ablyが保守するドライバの使用に関する詳細については、AblyのLaravelブロードキャスターのドキュメントを参照してください。[!NOTE]
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ファイルでブロードキャストドライバをablyに変更する必要があります。Next, you will need to change your broadcast driver to ably in your .env file:

BROADCAST_DRIVER=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.

オープンソースの代替Open Source Alternatives

NodeNode

Soketiは、NodeベースでPusher互換のLaravel用WebSocketサーバです。Soketiの内部では、µWebSockets.jsを利用し、極めて高いスケーラビリティとスピードを実現しています。このパッケージにより、商用WebSocketプロバイダを使用せずにLaravelブロードキャスティングの能力をフルに活用することができます。このパッケージのインストールと使用に関する詳細は、公式ドキュメントを参照してください。Soketi[https://github.com/soketi/soketi] is a Node based, Pusher compatible WebSocket server for Laravel. Under the hood, Soketi utilizes µWebSockets.js for extreme scalability and speed. This package allows you to leverage the full power of Laravel broadcasting without a commercial WebSocket provider. For more information on installing and using this package, please consult its official documentation[https://docs.soketi.app/].

クライアント側インストール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 Warning! Laravel Echoのreverbブロードキャスタには、laravel-echoのv1.16.0以上が必要です。[!WARNING]
The Laravel Echo reverb broadcaster requires laravel-echo v1.16.0 .

PusherチャンネルPusher Channels

Laravel EchoはJavaScriptライブラリであり、チャンネルをサブスクライブし、サーバ側のブロードキャストドライバがブロードキャストしたイベントを簡単にリッスンできます。NPMパッケージマネージャを介してEchoをインストールします。以下の例では、Pusher Channelsブロードキャスタを使用するため、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 we will be using the Pusher Channels broadcaster:

npm install --save-dev laravel-echo pusher-js

Echoをインストールできたら、アプリケーションのJavaScriptで新しいEchoインスタンスを生成する用意が整います。これを実行するのに最適な場所は、Laravelフレームワークに含まれているresources/js/bootstrap.jsファイルの下部です。デフォルトで、Echo設定の例はすでにこのファイルに含まれています。アンコメントするだけです。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:

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
});

アンコメントし、必要に応じEcho設定を調整したら、アプリケーションのアセットをコンパイルします。Once you have uncommented and adjusted the Echo configuration according to your needs, you may compile your application's assets:

npm run build

lightbulb Note: アプリケーションで使用しているJavaScriptリソースのコンパイルについて詳しく知りたい場合は、Viteドキュメントを参照してください。[!NOTE]
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

lightbulb Note: 以下のドキュメントでは、Ablyを「Pusher互換」モードで使用する方法について説明していきます。しかし、Ablyチームは、Ablyが提供するユニークな機能を活用できるブロードキャスターとEchoクライアントを推奨し、保守しています。Ablyが保守するドライバの使用に関する詳細については、AblyのLaravelブロードキャスターのドキュメントを参照してください。[!NOTE]
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ライブラリであり、チャンネルをサブスクライブして、サーバ側のブロードキャストドライバがブロードキャストしたイベントを簡単にリッスンできます。NPMパッケージマネージャを介してEchoをインストールします。この例では、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.

イベントのブロードキャストにAblyを使用しているのに、なぜpusher-jsJavaScriptライブラリをインストールするのか不思議に思うかもしれません。ありがたいことに、AblyにはPusher互換モードが含まれており、クライアント側アプリケーションでイベントをリッスンするときにPusherプロトコルを使用できます。You may wonder why we would install the pusher-js JavaScript library even though we are using Ably to broadcast our events. Thankfully, Ably includes a Pusher compatibility mode which lets us use the Pusher protocol when listening for events in our client-side application:

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インスタンスを生成する準備が整います。これを実行するのに最適な場所は、Laravelフレームワークに含まれているresources/js/bootstrap.jsファイルの下部です。デフォルトでは、Echo設定の例はすでにこのファイルに用意してあります。ただし、bootstrap.jsファイルのデフォルト設定はPusherを対象としています。以下の設定をコピーして、設定をAbly向きに変更できます。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; however, the default configuration in the bootstrap.js file is intended for Pusher. 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鍵の部分です。Note that 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 uncommented and adjusted the Echo configuration according to your needs, you may compile your application's assets:

npm run dev

lightbulb Note: アプリケーションで使用しているJavaScriptリソースのコンパイルについて詳しく知りたい場合は、Viteドキュメントを参照してください。[!NOTE]
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.

lightbulb Note: Pusherの代わりにオープンソースを使いたい場合は、オープンソースの代替を読んでください。[!NOTE]
If you would like to explore open source alternatives to Pusher, check out the open source alternatives[#open-source-alternatives].

サンプルアプリケーションの使用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);
}

If you wish the event to broadcast on multiple channels, you may return an array instead: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メソッドは、イベントがブロードキャストする必要があるチャンネルまたはチャンネルの配列を返す必要があります。チャンネルは、ChannelPrivateChannelPresenceChannelのインスタンスである必要があります。Channelインスタンスは、すべてのユーザーがサブスクライブできるパブリックチャンネルを表し、PrivateChannelsPresenceChannelsは、チャンネル認証を必要とするプライベートチャンネルを表します。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;
}

lightbulb 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; however, you do need to define the proper routes to respond to these requests.

認可ルートの定義Defining Authorization Routes

便利なことに、Laravelではチャンネル認可リクエストに応答するルートを簡単に定義できます。Laravelアプリケーションに含まれているApp\Providers\BroadcastServiceProviderで、Broadcast::routesメソッドの呼び出しが見つかるでしょう。このメソッドは、認可リクエストを処理するために/Broadcasting/authルートを登録します。Thankfully, Laravel makes it easy to define the routes to respond to channel authorization requests. In the App\Providers\BroadcastServiceProvider included with your Laravel application, you will see a call to the Broadcast::routes method. This method will register the /broadcasting/auth route to handle authorization requests:

Broadcast::routes();

Broadcast::routesメソッドは自動的にそのルートをwebミドルウェアグループ内に配置します。ただし、割り当てられた属性をカスタマイズする場合は、ルート属性の配列をメソッドに渡してください。The Broadcast::routes method will automatically place its routes within the web middleware group; however, you may pass an array of route attributes to the method if you would like to customize the assigned attributes:

Broadcast::routes($attributes);

認可エンドポイントのカスタマイズCustomizing the Authorization Endpoint

デフォルトでEchoは/Broadcasting/authエンドポイントを使用してチャンネルアクセスを認可します。ただし、authEndpoint設定オプションをEchoインスタンスに渡すことで、独自の認可エンドポイントを指定できます。By default, Echo will use the /broadcasting/auth endpoint to authorize channel access. However, you may specify your own authorization endpoint by passing the authEndpoint configuration option to your Echo instance:

window.Echo = new Echo({
    broadcaster: 'pusher',
    // ...
    authEndpoint: '/custom/endpoint/auth'
});

認可リクエストのカスタマイズCustomizing the Authorization Request

Laravel Echoの初期化時に、カスタムAuthorizerを指定し、Laravel Echoの認可リクエスト実行方法をカスタマイズできます。You can customize how Laravel Echo performs authorization requests by providing a custom authorizer when initializing Echo:

window.Echo = new Echo({
    // ...
    authorizer: (channel, options) => {
        return {
            authorize: (socketId, callback) => {
                axios.post('/api/broadcasting/auth', {
                    socket_id: socketId,
                    channel_name: channel.name
                })
                .then(response => {
                    callback(null, response.data);
                })
                .catch(error => {
                    callback(error);
                });
            }
        };
    },
})

認可コールバックの定義Defining Authorization Callbacks

次に、現在の認証済みユーザーが特定のチャンネルをリッスンできるかどうかを実際に決定するロジックを定義する必要があります。これは、アプリケーションに含まれている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 is included with your application. 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ルートモデルバインディングとは異なり、チャンネルモデルバインディングは自動暗黙的モデルバインディングスコープをサポートしていません。ただし、ほとんどのチャンネルは単一のモデルの一意の主キーに基づいてスコープを設定できるため、これが問題になることはめったにありません。[!WARNING]
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;
    }
}

lightbulb Note: Laravelの他の多くのクラスと同様に、チャンネルクラスはサービスコンテナによって自動的に依存解決されます。そのため、コンストラクターでチャンネルに必要な依存関係をタイプヒントすることができます。[!NOTE]
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表現を返す/taskURLにリクエストを送信する場合があります。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 Warning! toOthersメソッドを呼び出すには、イベントでIlluminate\Broadcasting\InteractsWithSocketsトレイトをuseする必要があります。[!WARNING]
Your event must use the Illuminate\Broadcasting\InteractsWithSockets trait in order to call the toOthers 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メソッドを公開するとともに、herejoining、および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のモデルブロードキャストサービスの一般的なコンセプトや、ブロードキャストイベントを手作業で作成したり、リッスンしたりする方法に精通しておくことをおすすめします。[!WARNING]
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引数を受け取っていることにお気づきでしょう。この引数には、モデルで発生したイベントの種類が含まれており、createdupdateddeletedtrashedrestoredのいずれかの値を持ちます。この変数の値を調べることで、必要であれば、特定のイベントに対しモデルをどのチャンネルへブロードキャストするかを判定できます。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.

つまり、id1App\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メソッドを呼び出してください。たとえば、1idを持つ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.

必要であれば、モデルに broadcastAsbroadcastWith メソッドを追加することで、カスタムのブロードキャスト名とペイロードを定義することができます。これらのメソッドは、発生しているモデルのイベント/操作の名前を受け取るので、モデルの操作ごとにイベントの名前やペイロードをカスタマイズできます。もし、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

lightbulb Note: Pusherチャンネルを使用する場合は、クライアントイベントを送信するためにアプリケーションダッシュボードの"App Settings"セクションの"Client Events"オプションを有効にする必要があります。[!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}チャンネルのチャンネル認可コールバックは、Laravelフレームワークに付属するデフォルトのBroadcastServiceProviderに含まれています。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 the default BroadcastServiceProvider that ships with the Laravel framework.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作