Readouble

Laravel master イベントブロードキャスト

イントロダクション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トークンにアクセスする必要があります。可能であれば、EchoはLaravel.csrfToken JavaScriptオブジェクトから、トークンを取得します。このオブジェクトは、make:auth Artisanコマンドを実行していれば、resources/views/layouts/app.blade.phpレイアウトで定義されています。このレイアウトを使用しない場合には、アプリケーションのhead HTMLエレメント中で、metaタグを定義する必要があります。Laravel Echo[#installing-laravel-echo] will need access to the current session's CSRF token. If available, Echo will pull the token from the Laravel.csrfToken JavaScript object. This object is defined in the resources/views/layouts/app.blade.php layout that is created if you run the make:auth Artisan command. If you are not using this layout, you may define a meta tag in your application's head HTML element:

<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

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

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

import Echo from "laravel-echo"

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サーバをペアリングする場合、アプリケーションのhead HTML要素で、Socket.IO JavaScriptクライアントライブラリをインクルードする必要があります。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's head HTML element:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

次に、socket.ioコネクタとhostを指定し、Echoをインスタンス化します。たとえば、アプリケーションとソケットサーバがapp.devドメイン上で動作している場合、Echoは次のようにインスタンス化します。Next, you will need to instantiate Echo with the socket.io connector and a host. For example, if your application and socket server are running on the app.dev domain you should instantiate Echo like so:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://app.dev: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[http://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 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[http://pusher.com] or Laravel Echo[#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
{
    //
}

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

プライベートチャンネルをリッスンするには、ユーザは認可されている必要があることを思い出してください。BroadcastServiceProviderbootメソッドで、チャンネルの認可ルールを定義してください。この例の場合、プライベートorder.1チャンネルをリッスンしようとするユーザは、実際にそのオーダーの発注者であることを確認しています。Remember, users must be authorized to listen on private channels. We may define our channel authorization rules in the boot method of the BroadcastServiceProvider. 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.*', 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"の部分を表しています。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 * character 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';
}

ブロードキャストデータ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';

認証中チャンネル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);

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

次に、チャンネル認可を実際に行うロジックを定義する必要があります。認可ルートと同様に、BroadcastServiceProviderbootメソッドの中で行います。このメソッドの中で、Broadcast::channelメソッドを使い、チャンネル認可コールバックを登録します。Next, we need to define the logic that will actually perform the channel authorization. Like defining the authorization routes, this is also done in the boot method of the BroadcastServiceProvider. In this method, you may use the Broadcast::channel method to register channel authorization callbacks:

Broadcast::channel('order.*', 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"の部分を表しています。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 * character to indicate that the "ID" portion of the channel name is a wildcard.

ブロードキャストイベント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:

this.$http.post('/task', task)
    .then((response) => {
        this.tasks.push(response.data);
    });

しかし、タスク生成のブロードキャストも行うことを思い出してください。もし、JavaScriptアプリケーションがタスクをリストへ追加するため、このイベントをリッスンしていれば、二重にタスクがリストへ追加されるでしょう。一つはエンドポイントから、もう一つはブロードキャストからです。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.

これを解決するために、toOthersメソッドを使い、ブロードキャスタへ現在のユーザには、イベントをブロードキャストしないように指示できます。You may solve this by using the toOthers method to instruct the broadcaster to not broadcast the event to the current user.

設定Configuration

Laravel Echoインスタンスを初期化する時、接続へソケットIDをアサインします。VueとVueリソースを使用していれば、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 Vue Resource, 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とVueリソースを使用しない場合、JavaScriptアプリケーションでX-Socket-IDヘッダーを送信するように、設定する必要があります。ソケットIDはEcho.socketIdメソッドにより取得できます。If you are not using Vue and Vue Resource, 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/assets/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/assets/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
});

イベントのリッスン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インスタンスのleaveメソッドを呼び出してください。To leave a channel, you may call the leave method on your Echo instance:

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.*', 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) => {
        //
    });

通知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.*チャンネルのチャンネル認可コールバックは、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.* 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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作