Readouble

Laravel 5.7 ブロードキャスト

イントロダクションIntroduction

多くの近代的なアプリケーションでは、リアルタイムでライブ更新されるユーザーインターフェイスを実装するために、WebSocketが使用されています。サーバ上で何かのデータが更新されると、通常WebSocket接続を通じメッセージが送信され、クライアントにより処理されます。これは変更をアプリケーションに対しポーリングし続ける方法よりも、強固で効率的です。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. This provides a more robust, efficient alternative to continually polling your application for changes.

こうしたタイプのアプリケーション構築を援助するため、LaravelはWebSocket接続経由で、イベントを簡単に「ブロードキャスト」できます。Laravelでイベントをブロードキャストすることにより、サーバサイドのコードとクライアントサイドのJavaScriptで、同じ名前のイベントを共有できます。To assist you in building these types of applications, Laravel makes it easy to "broadcast" your events[/docs/{{version}}/events] over a WebSocket connection. Broadcasting your Laravel events allows you to share the same event names between your server-side code and your client-side JavaScript application.

lightbulb">Tip!! ブロードキャストを開始する前に、Laravelのイベントとリスナに関するドキュメントをすべてしっかりと読んでください。{tip} Before diving into event broadcasting, make sure you have read all of the documentation regarding Laravel events and listeners[/docs/{{version}}/events].

設定Configuration

イベントブロードキャストの設定オプションは、すべてconfig/broadcasting.php設定ファイルの中にあります。Laravelはドライバをいくつか準備しています。PusherRedis、それにローカルの開発とデバッグのための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[https://pusher.com], 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. 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配列配列にある、このプロバイダのコメントを外してください。このプロバイダはブロードキャスト認証ルートとコールバックを登録します。Before broadcasting any events, you will first need to register the App\Providers\BroadcastServiceProvider. In fresh Laravel applications, you only need to uncomment this provider in the providers array of your config/app.php configuration file. This provider will allow you to register the broadcast authorization routes and callbacks.

CSRFトークンCSRF Token

Laravel Echoは、現在のセッションのCSRFトークンへアクセスする必要があります。アプリケーションのhead HTML要素を確認し、SCRFトークンを含むようにmetaタグを定義してください。Laravel Echo[#installing-laravel-echo] will need access to the current session's CSRF token. You should verify that your application's head HTML element defines a meta tag containing the CSRF token:

<meta name="csrf-token" content="{{ csrf_token() }}">

ドライバ要求Driver Prerequisites

PusherPusher

イベントをPusherによりブロードキャストする場合、Composerパッケージマネージャを使い、Pusher PHP SDKをインストールする必要があります。If you are broadcasting your events over Pusher[https://pusher.com], you should install the Pusher PHP SDK using the Composer package manager:

composer require pusher/pusher-php-server "~3.0"

次に、Pusherの認証情報をconfig/broadcasting.php設定ファイル中で設定する必要があります。Pusherの設定例はこのファイルに含まれ、Pusherキーと秘密キー、アプリケーションIDを簡単に指定できます。config/broadcasting.phpファイルのpusher設定では、Pusherでサポートされているクラスタなど、追加のオプション(options)も設定可能です。Next, you should configure your Pusher credentials in the config/broadcasting.php configuration file. An example Pusher configuration is already included in this file, allowing you to quickly specify your Pusher key, secret, and application ID. The config/broadcasting.php file's pusher configuration also allows you to specify additional options that are supported by Pusher, such as the cluster:

'options' => [
    'cluster' => 'eu',
    'encrypted' => true
],

PusherとLaravel Echoを使用する場合、resources/js/bootstrap.jsファイルのEchoインスタンスをインスタンス化する時に、使用するブロードキャスタとして、pusherを指定する必要があります。When using Pusher and Laravel Echo[#installing-laravel-echo], you should specify pusher as your desired broadcaster when instantiating the Echo instance in your resources/js/bootstrap.js file:

import Echo from "laravel-echo";

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key'
});

RedisRedis

Redisブロードキャスタを使用する場合は、Predisライブラリをインストールする必要があります。If you are using the Redis broadcaster, you should install the Predis library:

composer require predis/predis

RedisブロードキャスタはRedisのpub/sub機能を使用し、メッセージをブロードキャストします。Redisからのメッセージを受け、WebSocketチャンネルへブロードキャストできるように、これをWebSocketとペアリングする必要があります。The Redis broadcaster will broadcast messages using Redis' pub / sub feature; however, you will need to pair this with a WebSocket server that can receive the messages from Redis and broadcast them to your WebSocket channels.

Redisブロードキャスタがイベントを発行すると、そのイベントに指定されたチャンネル名へ発行され、イベント名、dataペイロード、イベントのソケットIDを生成したユーザー(該当する場合)を含む、ペイロードはJSONエンコードされた文字列になります。When the Redis broadcaster publishes an event, it will be published on the event's specified channel names and the payload will be a JSON encoded string containing the event name, a data payload, and the user that generated the event's socket ID (if applicable).

Socket.IOSocket.IO

RedisブロードキャスタとSocket.IOサーバをペアリングする場合、アプリケーションへSocket.IO JavaScriptクライアントライブラリをインクルードする必要があります。NPMパッケージマネージャにより、インストールできます。If you are going to pair the Redis broadcaster with a Socket.IO server, you will need to include the Socket.IO JavaScript client library in your application. You may install it via the NPM package manager:

npm install --save socket.io-client

次に、socket.ioコネクタとhostを指定し、Echoをインスタンス化します。Next, you will need to instantiate Echo with the socket.io connector and a host.

import Echo from "laravel-echo"

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname   ':6001'
});

最後に、Socket.IOのコンパチブルサーバを実行する必要があります。LaravelにはSocket.IOサーバの実装は含まれていません。しかし、tlaverdure/laravel-echo-server GitHubリポジトリで、コミュニティにより現在、Socket.IOサーバがメンテナンスされています。Finally, you will need to run a compatible Socket.IO server. Laravel does not include a Socket.IO server implementation; however, a community driven Socket.IO server is currently maintained at the tlaverdure/laravel-echo-server[https://github.com/tlaverdure/laravel-echo-server] GitHub repository.

キュー事前要件Queue Prerequisites

イベントをブロードキャストし始める前に、キューリスナを設定し、実行する必要もあります。イベントのブロードキャストは、すべてキュージョブとして行われるため、アプリケーションのレスポンスタイムにはシリアスな影響はでません。Before broadcasting events, you will also need to configure and run a queue listener[/docs/{{version}}/queues]. All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected.

概論Concept Overview

Laravelのイベントブロードキャストは、サーバサイドのLaravelイベントから、WebSocketに対する駆動ベースのアプローチを使っている、あなたのクライアントサイドのJavaScriptアプリケーションへ、ブロードキャストできるようにします。現在、PusherとRedisドライバーが用意されています。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[https://pusher.com] and Redis drivers. The events may be easily consumed on the client-side using the Laravel Echo[#installing-laravel-echo] 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コマースショップを使い、ハイレベルな概念を把握しましょう。このドキュメント中の別のセクションで詳細を説明するため、PusherLaravel Echoの設定についての詳細は省きます。Before diving into each component of event broadcasting, let's take a high level overview using an e-commerce store as an example. We won't discuss the details of configuring Pusher[https://pusher.com] or Laravel Echo[#installing-laravel-echo] since that will be discussed in detail in other sections of this documentation.

このアプリケーションでは、ユーザーに注文の発送状態を確認してもらうビューページがあるとしましょう。さらに、アプリケーションが発送状態を変更すると、ShippingStatusUpdatedイベントが発行されるとしましょう。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 a ShippingStatusUpdated event is fired when a shipping status update is processed by the application:

event(new ShippingStatusUpdated($update));

ShouldBroadcastインターフェイスThe ShouldBroadcast Interface

ユーザーがある注文を閲覧している時に、ビューの状態を変更するために、ユーザーがページを再読込しなくてはならないなんてしたくありません。代わりにアップデートがあることをアプリケーションへブロードキャストしたいわけです。そのため、ShouldBroadcastインターフェイスを実装した、ShippingStatusUpdatedイベントを作成する必要があります。このインターフェイスはイベントが発行されると、ブロードキャストすることを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 ShippingStatusUpdated event with the ShouldBroadcast interface. This will instruct Laravel to broadcast the event when it is fired:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ShippingStatusUpdated implements ShouldBroadcast
{
    /**
     * 発送状態更新の情報
     *
     * @var string
     */
    public $update;
}

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:

/**
 * イベントをブロードキャストすべき、チャンネルの取得
 *
 * @return array
 */
public function broadcastOn()
{
    return new PrivateChannel('order.'.$this->update->order_id);
}

認証中チャンネルAuthorizing Channels

プライベートチャンネルをリッスンするには、ユーザーは認可されている必要があることを思い出してください。routes/channels.phpファイルでチャンネルの認可ルールを定義してください。この例の場合、プライベートorder.1チャンネルをリッスンしようとするユーザーは、実際にそのオーダーの発注者であることを確認しています。Remember, users must be authorized to listen on private channels. We may define our channel authorization rules in the routes/channels.php file. In this example, we need to verify that any user attempting to listen on the private order.1 channel is actually the creator of the order:

Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});

channelメソッドは引数を2つ取ります。チャンネルの名前と、ユーザーにそのチャネルをリッスンする認可があるかどうかをtruefalseで返すコールバックです。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.

認可コールバックは、最初の引数に現在認証中のユーザーを受け取ります。引き続き、追加のプレースホルダパラメータを指定します。この例の場合、チャンネル名中で"ID"の部分を表す、{orderID}プレースホルダーを使っています。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メソッドを使います。それから、ShippingStatusUpdatedイベントをリッスンするために、listenメソッドを使用します。デフォルトでは、イベントのpublicプロパティは、すべてブロードキャストイベントに含まれています。Next, all that remains is to listen for the event in our JavaScript application. We can do this using Laravel Echo. First, we'll use the private method to subscribe to the private channel. Then, we may use the listen method to listen for the ShippingStatusUpdated event. By default, all of the event's public properties will be included on the broadcast event:

Echo.private('order.'   orderId)
    .listen('ShippingStatusUpdated', (e) => {
        console.log(e.update);
    });

ブロードキャストイベントの定義Defining Broadcast Events

Laravelへイベントをブロードキャストすることを知らせるためには、そのイベントクラスでIlluminate\Contracts\Broadcasting\ShouldBroadcastインターフェイスを実装します。このインターフェイスは、フレームワークにより生成されたすべてのイベントクラスで、useされていますので、イベントへ簡単に追加できます。To inform Laravel that a given event should be broadcast, 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インスタンスはユーザーが行動するパブリックチャンネルを表しています。一方、PrivateChannelPresenceChannelは、チャンネル認可が必要な、プライベートチャンネルを表しています。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 Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ServerCreated implements ShouldBroadcast
{
    use SerializesModels;

    public $user;

    /**
     * 新しいイベントインスタンスの生成
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * イベントをブロードキャストすべき、チャンネルの取得
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('user.'.$this->user->id);
    }
}

これで、あと必要なのは、通常通りにイベントを発行するだけです。イベントを発行すると、キュージョブが指定済みのドライバを通して、自動的にそのイベントをブロードキャストします。Then, 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 over 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:

/**
 * イベントブロードキャスト名
 *
 * @return string
 */
public function broadcastAs()
{
    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アプリケーションより、publicデータにアクセスできます。ですから、たとえば、あるイベントにEloquentモデルを含む、publicの$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
 */
public function broadcastWith()
{
    return ['id' => $this->user->id];
}

ブロードキャストキューBroadcast Queue

デフォルトでは各ブロードキャストイベントは、queue.php設定ファイルで指定されているデフォルトキュー接続の、デフォルトキューへ投入されます。イベントクラスのbroadcastQueueプロパティを定義することにより、使用するキューをカスタマイズできます。このプロパティには、ブロードキャスト時に使用したいキューの名前を指定してください。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 used by the broadcaster by defining a broadcastQueue property on your event class. This property should specify the name of the queue you wish to use when broadcasting:

/**
 * イベントを投入するキューの名前
 *
 * @var string
 */
public $broadcastQueue = 'your-queue-name';

デフォルトキュードライバーの代わりに、syncキューを使いイベントをブロードキャストする場合、ShouldBroadcastの代わりにShouldBroadcastNowインターフェイスを実装してください。If you want 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 ShippingStatusUpdated implements ShouldBroadcastNow
{
    //
}

ブロードキャスト条件Broadcast Conditions

指定した条件がtrueの場合のみ、ブロードキャストを行いたい場合もあるでしょう。イベントクラスへ、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:

/**
 * このイベントでブロードキャストするかを決定
 *
 * @return bool
 */
public function broadcastWhen()
{
    return $this->value > 100;
}

認証中チャンネル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[#installing-laravel-echo], 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アプリケーションに含まれているBroadcastServiceProviderで、Broadcast::routesメソッドが呼びだされているのが見つかります。このメソッドが認可リクエストを処理する、/broadcasting/authルートを登録しています。Thankfully, Laravel makes it easy to define the routes to respond to channel authorization requests. In the 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エンドポイントを使用します。しかしながら、EchoインスタンスへauthEndpoint設定オプションを渡せば、独自の認可エンドポイントを指定できます。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',
    key: 'your-pusher-key',
    authEndpoint: '/custom/endpoint/auth'
});

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

次に、チャンネル認可を実際に行うロジックを定義する必要があります。アプリケーションに含まれる、routes/channels.phpファイルで行います。このメソッドの中で、Broadcast::channelメソッドを使い、チャンネル認可コールバックを登録します。Next, we need to define the logic that will actually perform the channel authorization. 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:

Broadcast::channel('order.{orderId}', function ($user, $orderId) {
    return $user->id === Order::findOrNew($orderId)->user_id;
});

channelメソッドは引数を2つ取ります。チャンネルの名前と、ユーザーにそのチャネルをリッスンする認可があるかどうかをtruefalseで返すコールバックです。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.

認可コールバックは、最初の引数に現在認証中のユーザーを受け取ります。引き続き、追加のプレースホルダパラメータを指定します。この例の場合、チャンネル名中で"ID"の部分を表す、{orderID}プレースホルダーを使っています。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.

認証コールバックモデル結合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 the string or numeric order ID, you may request an actual Order model instance:

use App\Order;

Broadcast::channel('order.{order}', function ($user, Order $order) {
    return $user->id === $order->user_id;
});

チャンネル名の登録Defining Channel Classes

アプリケーションで多くのチャンネルを利用していると、routes/channels.phpファイルは膨大になってしまいます。認証チャンネルのクロージャを使用する代わりに、チャンネルクラスを使用するのが良いでしょう。チャンネルクラスを生成するには、make:channel Aritisanコマンドが使用できます。このコマンドは、新しいチャンネルクラスを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('order.{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\User;
use App\Order;

class OrderChannel
{
    /**
     * 新しいチャンネルインスタンスの生成
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * ユーザーのチャンネルへアクセスを認証
     *
     * @param  \App\User  $user
     * @param  \App\Order  $order
     * @return array|bool
     */
    public function join(User $user, Order $order)
    {
        return $user->id === $order->user_id;
    }
}

lightbulb">Tip!! Laravelの他のクラスと同様に、チャンネルクラスは自動的にサービスコンテナにより、依存を解決されます。そのため、コンストラクタでタイプヒントにより、チャンネルで必要な依存を指定できます。{tip} 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インターフェイスを実装したら、あとはevent関数を使い、イベントを発行するだけです。イベントディスパッチャは、そのイベントがShouldBroadcastインターフェイスにより印付けられていることに注目しており、ブロードキャストするためにイベントをキューへ投入します。Once you have defined an event and marked it with the ShouldBroadcast interface, you only need to fire the event using the event function. The event dispatcher will notice that the event is marked with the ShouldBroadcast interface and will queue the event for broadcasting:

event(new ShippingStatusUpdated($update));

認証中ユーザーの回避Only To Others

イベントブロードキャストを使用するアプリケーションを構築しているとき、event関数をbroadcast関数へ置き換えることもできます。event関数と同様に、broadcast関数もイベントをサーバサイドリスナへディスパッチします。When building an application that utilizes event broadcasting, you may substitute the event function with the broadcast function. Like the event function, the broadcast function dispatches the event to your server-side listeners:

broadcast(new ShippingStatusUpdated($update));

しかし、broadcast関数には、ブロードキャストの受取人から現在のユーザーを除外できる、toOthersメソッドが用意されています。However, the broadcast function also exposes the toOthers method which allows you to exclude the current user from the broadcast's recipients:

broadcast(new ShippingStatusUpdated($update))->toOthers();

toOthersメソッドをいつ使うのかをよく理解してもらうため、タスク名を入力してもらうことにより新しいタスクをユーザーが作成できる、タスクリストアプリケーションを想像してください。タスクを作成するためにアプリケーションは、タスクの生成をブロードキャストし、新しいタスクのJSON表現を返す、/taskエンドポイントへリクエストを作成するでしょう。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 end-point 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アプリケーションがこのイベントをタスクリストへタスクを追加するためにリッスンしている場合、リストにそのタスクを二重登録してしまいます。ひとつはエンドポイントから、もう一つはブロードキャストからです。これを解決するには、toOthers`メソッドを使用し、ブロードキャスターへそのイベントを現在のユーザーに対してブロードキャストしないように指示してください。However, remember that we also broadcast the task's creation. If your JavaScript application is 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.

Note: note イベントでtoOthersメソッドを呼び出すには、Illuminate\Broadcasting\InteractsWithSocketsトレイトを使用する必要があります。{note} Your event must use the Illuminate\Broadcasting\InteractsWithSockets trait in order to call the toOthers method.

設定Configuration

Laravel Echoインスタンスを初期化する時、接続へソケットIDをアサインします。VueAxiosを使用していれば、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 Vue[https://vuejs.org] and Axios[https://github.com/mzabriskie/axios], the socket ID will automatically be attached to every outgoing request as a 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.

VueとAxiosを使用しない場合、JavaScriptアプリケーションでX-Socket-IDヘッダを送信するように、設定する必要があります。ソケットIDはEcho.socketIdメソッドにより取得できます。If you are not using Vue and Axios, you will need to manually configure your JavaScript application to send the X-Socket-ID header. You may retrieve the socket ID using the Echo.socketId method:

var socketId = Echo.socketId();

ブロードキャストの受け取りReceiving Broadcasts

Laravel EchoのインストールInstalling Laravel Echo

Laravel EchoはJavaScriptライブラリで、チャンネルの購読とLaravelによるイベントブロードキャストのリッスンを苦労なしに実現してくれます。EchoはNPMパッケージマネージャにより、インストールします。以降の例で、Pusherブロードキャストを使用する予定のため、pusher-jsパッケージもインストールしています。Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. 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 broadcaster:

npm install --save laravel-echo pusher-js

Echoがインストールできたら、アプリケーションのJavaScriptで、真新しいEchoインスタンスを作成する準備が整いました。これを行うには、Laravelフレームワークに含まれている、resources/js/bootstrap.jsファイルの最後が、良いでしょう。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:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key'
});

pusherコネクタを使うEchoインスタンスを作成するときには、clusterと同時に接続の暗号化を行うかどうかを指定することもできます。When creating an Echo instance that uses the pusher connector, you may also specify a cluster as well as whether the connection should be encrypted:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    cluster: 'eu',
    encrypted: true
});

既存クライアントインスタンスの利用Using An Existing Client Instance

Echoで使用したいPusherやSocket.ioクライアントを既に用意してあれば、client設定オプションによりEchoへ指定できます。If you already have a Pusher or Socket.io client instance that you would like Echo to utilize, you may pass it to Echo via the client configuration option:

const client = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-key',
    client: client
});

イベントのリッスンListening For Events

インストールが済み、Echoをインスタンス化したら、イベントブロードキャストをリスニングする準備が整いました。最初に、channelメソッドを使い、チャンネルインスタンスを取得し、それからlistenメソッドで特定のイベントをリッスンしてください。Once you have installed and instantiated Echo, you are ready to start listening for event broadcasts. 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')
    .listen('OrderShipped', (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')
    .listen(...)
    .listen(...)
    .listen(...);

チャンネルの離脱Leaving A Channel

チャンネルを離脱するには、EchoインスタンスのleaveChannelメソッドを呼び出してください。To leave a channel, you may call the leaveChannel method on your Echo instance:

Echo.leaveChannel('orders');

チャンネルを離脱し、関連するプライベートチャンネル、現在のチャンネルも離脱したい場合は、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');

名前空間Namespaces

上の例で、イベントクラスの完全な名前空間を指定していないことに、皆さん気がついたでしょう。その理由は、EchoはイベントがApp\Events名前空間へ設置されると仮定しているからです。しかし、ルートの名前空間を設定変更している場合は、Echoのインスタンス化時に、namespace設定オプションを渡してください。You may have noticed in the examples above that we did not specify the full 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',
    key: 'your-pusher-key',
    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.

プレゼンスチャンネルの許可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アプリケーションのプレゼンスチャンネルイベントリスナで利用できるようになります。ユーザーがプレゼンスチャンネルへ参加する許可がない場合は、falsenullを返してください。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:

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    if ($user->canJoinRoom($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
    }
});

プレゼンスチャンネルへの参加Joining Presence Channels

プレゼンスチャンネルへ参加するには、Echoのjoinメソッドを使用します。joinメソッドは、既に説明したlistenメソッドに付け加え、herejoiningleavingイベントを購入できるようになっている、PresenceChannel実装を返します。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);
    });

hereコールバックはチャンネル参加に成功すると、すぐに実行されます。そして、このチャンネルを現在購入している、他の全ユーザー情報を含む配列を返します。joiningメソッドは、チャンネルに新しいユーザーが参加した時に実行されます。一方のleavingメソッドは、ユーザーがチャンネルから離脱した時に実行されます。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.

プレゼンスチャンネルへのブロードキャスト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 Channel|array
 */
public function broadcastOn()
{
    return new PresenceChannel('room.'.$this->message->room_id);
}

パブリックやプライベートイベントと同様に、プレゼンスチャンネルイベントはbroadcast関数を使用し、ブロードキャストされます。他のイベントと同様に、ブロードキャストから受けるイベントから、現在のユーザーを除くために、toOthersメソッドも利用できます。Like public or private events, presence channel events may be broadcast using the broadcast function. As with other events, you may use the toOthers method to exclude the current user from receiving the broadcast:

broadcast(new NewMessage($message));

broadcast(new NewMessage($message))->toOthers();

Echoのlistenメソッドにより、参加イベントをリッスンできます。You may listen for the join event via Echo's listen method:

Echo.join('chat.'   roomId)
    .here(...)
    .joining(...)
    .leaving(...)
    .listen('NewMessage', (e) => {
        //
    });

クライアントイベントClient Events

lightbulb">Tip!! Pusherを使用する場合、クライアントイベントを送信するために、application dashboardの"App Settings"にある、"Client Events"オプションを有効にしてください。{tip} When using Pusher[https://pusher.com], 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')
    .whisper('typing', {
        name: this.user.name
    });

クライアントイベントをリッスンするには、listenForWhisperメソッドを使います。To listen for client events, you may use the listenForWhisper method:

Echo.private('chat')
    .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. First, 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.User.'   userId)
    .notification((notification) => {
        console.log(notification.type);
    });

上記の例の場合、「ブロードキャスト」チャンネルを通じ、App\Userインスタンスへ送られる通知はすべて、コールバックにより受け取られます。App.User.{id}チャンネルのチャンネル認可コールバックは、Laravelフレームワークに用意されている、デフォルトのBroadcastServiceProviderに含まれています。In this example, all notifications sent to App\User instances via the broadcast channel would be received by the callback. A channel authorization callback for the App.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!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作