Readouble

Laravel 8.x 通知

イントロダクションIntroduction

メールの送信のサポートに加えて、LaravelはメールやSMS(Vonage経由、以前はNexmoとして知られていました)およびSlackなど、さまざまな配信チャンネルで通知を送信するためのサポートを提供しています。さらに、さまざまなコミュニティが構築した通知チャンネルが作成され、数十の異なるチャンネルで通知を送信できます!通知はWebインターフェイスに表示するため、データベースに保存される場合もあります。In addition to support for sending email[/docs/{{version}}/mail], Laravel provides support for sending notifications across a variety of delivery channels, including email, SMS (via Vonage[https://www.vonage.com/communications-apis/], formerly known as Nexmo), and Slack[https://slack.com]. In addition, a variety of community built notification channels[https://laravel-notification-channels.com/about/#suggesting-a-new-channel] have been created to send notification over dozens of different channels! Notifications may also be stored in a database so they may be displayed in your web interface.

通常、通知はアプリケーションで何かが起きたことをユーザーへ知らせる、短い情報メッセージです。たとえば、課金アプリを作成しているなら、メールとSMSチャンネルで「課金支払い」を送信できます。Typically, notifications should be short, informational messages that notify users of something that occurred in your application. For example, if you are writing a billing application, you might send an "Invoice Paid" notification to your users via the email and SMS channels.

通知の生成Generating Notifications

Laravelでは、各通知は通常、app/Notificationsディレクトリに保存される単一のクラスで表します。アプリケーションにこのディレクトリが存在しなくても心配しないでください。make:notification Artisanコマンドを実行すると作成されます。In Laravel, each notification is represented by a single class that is typically stored in the app/Notifications directory. Don't worry if you don't see this directory in your application - it will be created for you when you run the make:notification Artisan command:

php artisan make:notification InvoicePaid

このコマンドは app/Notificationsディレクトリに新しい通知クラスを配置します。各通知クラスはviaメソッドとtoMailtoDatabaseなどのメッセージ構築メソッドを含み、通知を特定のチャンネルに合わせたメッセージに変換します。This command will place a fresh notification class in your app/Notifications directory. Each notification class contains a via method and a variable number of message building methods, such as toMail or toDatabase, that convert the notification to a message tailored for that particular channel.

通知の送信Sending Notifications

Notifiableトレイトの使用Using The Notifiable Trait

通知は、Notifiableトレイトのnotifyメソッドを使用する方法と、Notificationファサードを使用する方法の2つの方法で送信できます。Notifiableトレイトは、アプリケーションのApp\Models\Userモデルにデフォルトで含まれています。Notifications may be sent in two ways: using the notify method of the Notifiable trait or using the Notification facade[/docs/{{version}}/facades]. The Notifiable trait is included on your application's App\Models\User model by default:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;
}

このトレイトが提供するnotifyメソッドは、通知インスタンスを引数に受けます。The notify method that is provided by this trait expects to receive a notification instance:

use App\Notifications\InvoicePaid;

$user->notify(new InvoicePaid($invoice));

lightbulb">Tip!! どのモデルでもNotifiableトレイトを使用できることを忘れないでください。Userモデルに含めるだけに限定されません。{tip} Remember, you may use the Notifiable trait on any of your models. You are not limited to only including it on your User model.

Notificationファサードの使用Using The Notification Facade

別のやり方として、Notificationファサードを介して通知を送信することもできます。このアプローチは、ユーザーのコレクションなど、複数の通知エンティティに通知を送信する必要がある場合に役立ちます。ファサードを使用して通知を送信するには、すべてのnotifiableエンティティと通知インスタンスをsendメソッドに渡します。Alternatively, you may send notifications via the Notification facade[/docs/{{version}}/facades]. This approach is useful when you need to send a notification to multiple notifiable entities such as a collection of users. To send notifications using the facade, pass all of the notifiable entities and the notification instance to the send method:

use Illuminate\Support\Facades\Notification;

Notification::send($users, new InvoicePaid($invoice));

sendNowメソッドを使って通知をすぐに送信することもできます。このメソッドは、通知が ShouldQueue インターフェイスを実装していても、通知を直ちに送信します。You can also send notifications immediately using the sendNow method. This method will send the notification immediately even if the notification implements the ShouldQueue interface:

Notification::sendNow($developers, new DeploymentCompleted($deployment));

配信チャンネルの指定Specifying Delivery Channels

通知を配信するチャンネルを指定するため、すべての通知クラスはviaメソッドを持っています。通知はmaildatabasebroadcastnexmoslackへ送れるようになっています。Every notification class has a via method that determines on which channels the notification will be delivered. Notifications may be sent on the mail, database, broadcast, nexmo, and slack channels.

lightbulb">Tip!! TelegramやPusherのような、他の配信チャンネルを利用したい場合は、コミュニティが管理している、Laravel Notification Channels websiteをご覧ください。{tip} If you would like to use other delivery channels such as Telegram or Pusher, check out the community driven Laravel Notification Channels website[http://laravel-notification-channels.com].

viaメソッドは、通知を送っているクラスのインスタンスである、$notifiableインスタンスを引数に受け取ります。$notifiableを使い、通知をどこに配信するチャンネルなのかを判定できます。The via method receives a $notifiable instance, which will be an instance of the class to which the notification is being sent. You may use $notifiable to determine which channels the notification should be delivered on:

/**
 * 通知の配信チャンネルを取得
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return $notifiable->prefers_sms ? ['nexmo'] : ['mail', 'database'];
}

通知のキューイングQueueing Notifications

Note: note 通知をキューへ投入する前に、キューを設定してワーカを起動する必要があります。{note} Before queueing notifications you should configure your queue and start a worker[/docs/{{version}}/queues].

通知の送信には時間がかかる場合があります。特に、チャンネルが通知を配信するために外部API呼び出しを行う必要がある場合に当てはまります。アプリケーションのレスポンス時間を短縮するには、クラスにShouldQueueインターフェイスとQueueableトレイトを追加して、通知をキューに入れてください。インターフェイスとトレイトは、make:notificationコマンドを使用して生成されたすべての通知であらかじめインポートされているため、すぐに通知クラスに追加できます。Sending notifications can take time, especially if the channel needs to make an external API call to deliver the notification. To speed up your application's response time, let your notification be queued by adding the ShouldQueue interface and Queueable trait to your class. The interface and trait are already imported for all notifications generated using the make:notification command, so you may immediately add them to your notification class:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    // ...
}

ShouldQueueインターフェイスを通知クラスへ追加したら、通常通りに送信してください。LaravelはクラスのShouldQueueインターフェイスを見つけ、自動的に通知の配信をキューへ投入します。Once the ShouldQueue interface has been added to your notification, you may send the notification like normal. Laravel will detect the ShouldQueue interface on the class and automatically queue the delivery of the notification:

$user->notify(new InvoicePaid($invoice));

通知の配信を遅らせたい場合、delayメソッドを通知のインスタンスへチェーンしてください。If you would like to delay the delivery of the notification, you may chain the delay method onto your notification instantiation:

$delay = now()->addMinutes(10);

$user->notify((new InvoicePaid($invoice))->delay($delay));

特定のチャンネルの遅​​延量を指定するため、配列をdelayメソッドに渡せます。You may pass an array to the delay method to specify the delay amount for specific channels:

$user->notify((new InvoicePaid($invoice))->delay([
    'mail' => now()->addMinutes(5),
    'sms' => now()->addMinutes(10),
]));

通知をキューへ投入すると、受信者とチャンネルの組み合わせごとにキュー投入済みジョブが作成されます。たとえば、通知に3つの受信者と2つのチャンネルがある場合、6つのジョブがキューにディスパッチされます。When queueing notifications, a queued job will be created for each recipient and channel combination. For example, six jobs will be dispatched to the queue if your notification has three recipients and two channels.

通知キュー接続のカスタマイズCustomizing The Notification Queue Connection

キューへ投入した通知は、アプリケーションのデフォルトのキュー接続を使用してキュー投入します。特定の通知に別の接続を使用する必要がある場合は、通知クラスに$connectionプロパティを定義します。By default, queued notifications will be queued using your application's default queue connection. If you would like to specify a different connection that should be used for a particular notification, you may define a $connection property on the notification class:

/**
 * 通知をキューに入れるときに使用するキュー接続名
 *
 * @var string
 */
public $connection = 'redis';

通知チャンネルキューのカスタマイズCustomizing Notification Channel Queues

各通知チャンネルが使用し、その通知がサポートしている特定のキューを指定する場合、通知へviaQueuesメソッドを定義してください。このメソッドはチャンネル名/キュー名のペアの配列を返してください。If you would like to specify a specific queue that should be used for each notification channel supported by the notification, you may define a viaQueues method on your notification. This method should return an array of channel name / queue name pairs:

/**
 * 各通知チャンネルで使用するキューを判断。
 *
 * @return array
 */
public function viaQueues()
{
    return [
        'mail' => 'mail-queue',
        'slack' => 'slack-queue',
    ];
}

キュー投入する通知とデータベーストランザクションQueued Notifications & Database Transactions

キューへ投入した通知がデータベーストランザクション内でディスパッチされると、データベーストランザクションがコミットされる前にキューによって処理される場合があります。これが発生した場合、データベーストランザクション中にモデルまたはデータベースレコードに加えた更新は、データベースにまだ反映されていない可能性があります。さらに、トランザクション内で作成されたモデルまたはデータベースレコードは、データベースに存在しない可能性があります。通知がこれらのモデルに依存している場合、キューに入れられた通知を送信するジョブが処理されるときに予期しないエラーが発生する可能性があります。When queued notifications 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 notification depends on these models, unexpected errors can occur when the job that sends the queued notification is processed.

キュー接続のafter_commit設定オプションがfalseに設定されている場合でも、通知時にafterCommitメソッドを呼び出せば、キュー投入する特定の通知をオープンしている全データベーストランザクションをコミットした後に、ディスパッチするよう指定できます。If your queue connection's after_commit configuration option is set to false, you may still indicate that a particular queued notification should be dispatched after all open database transactions have been committed by calling the afterCommit method when sending the notification:

use App\Notifications\InvoicePaid;

$user->notify((new InvoicePaid($invoice))->afterCommit());

あるいは、通知のコンストラクタから、afterCommitメソッドを呼び出すこともできます。Alternatively, you may call the afterCommit method from your notification's constructor:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * 新しいメッセージインスタンスの生成
     *
     * @return void
     */
    public function __construct()
    {
        $this->afterCommit();
    }
}

lightbulb">Tip!! この問題の回避方法の詳細は、キュー投入されるジョブとデータベーストランザクションに関するドキュメントを確認してください。{tip} 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].

キュー投入した通知を送信するか判定Determining If A Queued Notification Should Be Sent

バックグラウンド処理のため、通知をキューへディスパッチすると、通常はキューワーカがそれを受け取り、意図した受信者へ送信します。After a queued notification has been dispatched for the queue for background processing, it will typically be accepted by a queue worker and sent to its intended recipient.

しかし、キューワーカが処理した後に、そのキュー投入済み通知を送信すべきか最終的に判断したい場合は、通知クラスにshouldSendメソッドを定義してください。このメソッドからfalseを返す場合、通知は送信されません。However, if you would like to make the final determination on whether the queued notification should be sent after it is being processed by a queue worker, you may define a shouldSend method on the notification class. If this method returns false, the notification will not be sent:

/**
 * 通知を送信する必要があるかどうか確認
 *
 * @param  mixed  $notifiable
 * @param  string  $channel
 * @return bool
 */
public function shouldSend($notifiable, $channel)
{
    return $this->invoice->isPaid();
}

オンデマンド通知On-Demand Notifications

アプリケーションの「ユーザー」として保存されていない人に通知を送信する必要がある場合があります。Notificationファサードのrouteメソッドを使用して、通知を送信する前にアドホックな通知ルーティング情報を指定します。Sometimes you may need to send a notification to someone who is not stored as a "user" of your application. Using the Notification facade's route method, you may specify ad-hoc notification routing information before sending the notification:

Notification::route('mail', 'taylor@example.com')
            ->route('nexmo', '5555555555')
            ->route('slack', 'https://hooks.slack.com/services/...')
            ->notify(new InvoicePaid($invoice));

オンデマンド通知をmailルートへ送信するとき、受信者名を指定したい場合は、メールアドレスをキーとし、名前を配列の最初の要素の値として含む配列を渡してください。If you would like to provide the recipient's name when sending an on-demand notification to the mail route, you may provide an array that contains the email address as the key and the name as the value of the first element in the array:

Notification::route('mail', [
    'barrett@example.com' => 'Barrett Blair',
])->notify(new InvoicePaid($invoice));

メール通知Mail Notifications

メールメッセージのフォーマットFormatting Mail Messages

通知が電子メール送信をサポートしている場合は、通知クラスでtoMailメソッドを定義する必要があります。このメソッドは$notifiableエンティティを受け取り、Illuminate\Notifications\Messages\MailMessageインスタンスを返す必要があります。If a notification supports being sent as an email, you should define a toMail method on the notification class. This method will receive a $notifiable entity and should return an Illuminate\Notifications\Messages\MailMessage instance.

MailMessageクラスには、トランザクションメールメッセージの作成に役立ついくつかの簡単なメソッドが含まれています。メールメッセージには、「行動を促すフレーズ」だけでなく、テキスト行も含まれる場合があります。toMailメソッドの例を見てみましょう。The MailMessage class contains a few simple methods to help you build transactional email messages. Mail messages may contain lines of text as well as a "call to action". Let's take a look at an example toMail method:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    $url = url('/invoice/'.$this->invoice->id);

    return (new MailMessage)
                ->greeting('Hello!')
                ->line('課金が支払われました。')
                ->action('インボイス確認', $url)
                ->line('私達のアプリケーションをご利用いただき、ありがとうございます。');
}

lightbulb">Tip!! toMailメソッドの中で、$this->invoice->idを使っていることに注意してください。通知メッセージを生成するために必要な情報は、どんなものでも通知のコンストラクタへ渡せます。{tip} Note we are using $this->invoice->id in our toMail method. You may pass any data your notification needs to generate its message into the notification's constructor.

この例では、挨拶、テキスト行、行動を促すフレーズ、そして別のテキスト行を登録します。MailMessageオブジェクトが提供するこれらのメソッドにより、小さなトランザクションメールを簡単かつ迅速にフォーマットできます。次に、メールチャンネルは、メッセージコンポーネントを、平文テキストと対応する美しいレスポンス性の高いHTML電子メールテンプレートに変換します。mailチャンネルが生成する電子メールの例を次に示します。In this example, we register a greeting, a line of text, a call to action, and then another line of text. These methods provided by the MailMessage object make it simple and fast to format small transactional emails. The mail channel will then translate the message components into a beautiful, responsive HTML email template with a plain-text counterpart. Here is an example of an email generated by the mail channel:

lightbulb">Tip!! メール通知を送信するときは、必ずconfig/app.php設定ファイルでname設定オプションを設定してください。この値は、メール通知メッセージのヘッダとフッターに使用されます。{tip} When sending mail notifications, be sure to set the name configuration option in your config/app.php configuration file. This value will be used in the header and footer of your mail notification messages.

その他のメール通知フォーマットオプションOther Mail Notification Formatting Options

通知クラスの中にテキストの「行(line)」を定義する代わりに、通知メールをレンダーするためのカスタムテンプレートをviewメソッドを使い、指定できます。Instead of defining the "lines" of text in the notification class, you may use the view method to specify a custom template that should be used to render the notification email:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)->view(
        'emails.name', ['invoice' => $this->invoice]
    );
}

viewメソッドに与える配列の2番目の要素としてビュー名を渡すことにより、メールメッセージの平文テキストビューを指定できます。You may specify a plain-text view for the mail message by passing the view name as the second element of an array that is given to the view method:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)->view(
        ['emails.name.html', 'emails.name.plain'],
        ['invoice' => $this->invoice]
    );
}

エラーメッセージError Messages

一部の通知は、請求書の支払いの失敗などのエラーをユーザーに通知します。メッセージを作成するときにerrorメソッドを呼び出すことにより、メールメッセージがエラーに関するものであることを示すことができます。メールメッセージでerrorメソッドを使用すると、行動を促すフレーズのボタンが黒ではなく赤になります。Some notifications inform users of errors, such as a failed invoice payment. You may indicate that a mail message is regarding an error by calling the error method when building your message. When using the error method on a mail message, the call to action button will be red instead of black:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Message
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->error()
                ->subject('Notification Subject')
                ->line('...');
}

送信者のカスタマイズCustomizing The Sender

デフォルトのメール送信者/Fromアドレスは、config/mail.php設定ファイルで定義されています。しかし、特定の通知でFromアドレスを指定する場合は、fromメソッドで指定します。By default, the email's sender / from address is defined in the config/mail.php configuration file. However, you may specify the from address for a specific notification using the from method:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->from('barrett@example.com', 'Barrett Blair')
                ->line('...');
}

受信者のカスタマイズCustomizing The Recipient

mailチャンネルを介して通知を送信すると、通知システムは通知エンティティのemailプロパティを自動的に検索します。通知エンティティでrouteNotificationForMailメソッドを定義することにより、通知の配信に使用される電子メールアドレスをカスタマイズできます。When sending notifications via the mail channel, the notification system will automatically look for an email property on your notifiable entity. You may customize which email address is used to deliver the notification by defining a routeNotificationForMail method on the notifiable entity:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * メールチャンネルに対する通知をルートする
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return array|string
     */
    public function routeNotificationForMail($notification)
    {
        // メールアドレスのみを返す場合
        return $this->email_address;

        // メールアドレスと名前を返す場合
        return [$this->email_address => $this->name];
    }
}

件名のカスタマイズCustomizing The Subject

デフォルトでは、電子メールの件名は「タイトルケース」にフォーマットされた通知のクラス名です。したがって、通知クラスの名前がInvoicePaidの場合、メールの件名はInvoice Paidになります。メッセージに別の件名を指定する場合は、メッセージを作成するときに「subject」メソッドを呼び出します。By default, the email's subject is the class name of the notification formatted to "Title Case". So, if your notification class is named InvoicePaid, the email's subject will be Invoice Paid. If you would like to specify a different subject for the message, you may call the subject method when building your message:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->subject('Notification Subject')
                ->line('...');
}

MailerのカスタマイズCustomizing The Mailer

デフォルトでは、電子メール通知は、config/mail.php設定ファイルで定義しているデフォルトのメーラーを使用して送信されます。ただし、メッセージの作成時にmailerメソッドを呼び出すことにより、実行時に別のメーラーを指定できます。By default, the email notification will be sent using the default mailer defined in the config/mail.php configuration file. However, you may specify a different mailer at runtime by calling the mailer method when building your message:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->mailer('postmark')
                ->line('...');
}

テンプレートのカスタマイズCustomizing The Templates

通知パッケージのリソースをリソース公開することにより、メール通知で使用されるHTMLと平文テキストのテンプレートを変更することが可能です。次のコマンドを実行した後、メール通知のテンプレートはresources/views/vendor/notificationsディレクトリ下に作成されます。You can modify the HTML and plain-text template used by mail notifications by publishing the notification package's resources. After running this command, the mail notification templates will be located in the resources/views/vendor/notifications directory:

php artisan vendor:publish --tag=laravel-notifications

添付Attachments

電子メール通知に添付ファイルを追加するには、メッセージの作成中にattachメソッドを使用します。attachメソッドは、ファイルへの絶対パスを最初の引数に受けます。To add attachments to an email notification, use the attach method while building your message. The attach method accepts the absolute path to the file as its first argument:

/**
 * 通知のメール表現の取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->greeting('Hello!')
                ->attach('/path/to/file');
}

メッセージにファイルを添付するとき、attachメソッドの第2引数として配列を渡し、表示名やMIMEタイプの指定もできます。When attaching files to a message, you may also specify the display name and / or MIME type by passing an array as the second argument to the attach method:

/**
 * 通知のメール表現の取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->greeting('Hello!')
                ->attach('/path/to/file', [
                    'as' => 'name.pdf',
                    'mime' => 'application/pdf',
                ]);
}

Mailableオブジェクトにファイルを添付するのとは異なり、attachFromStorageを使用してストレージディスクから直接ファイルを添付することはできません。むしろ、ストレージディスク上のファイルへの絶対パスを指定してattachメソッドを使用する必要があります。または、toMailメソッドからmailableを返すこともできます。Unlike attaching files in mailable objects, you may not attach a file directly from a storage disk using attachFromStorage. You should rather use the attach method with an absolute path to the file on the storage disk. Alternatively, you could return a mailable[/docs/{{version}}/mail#generating-mailables] from the toMail method:

use App\Mail\InvoicePaid as InvoicePaidMailable;

/**
 * 通知のメール表現の取得
 *
 * @param  mixed  $notifiable
 * @return Mailable
 */
public function toMail($notifiable)
{
    return (new InvoicePaidMailable($this->invoice))
                ->to($notifiable->email)
                ->attachFromStorage('/path/to/file');
}

素のデータの添付Raw Data Attachments

attachDataメソッドを使用して、生のバイト文字列を添付ファイルとして添付できます。attachDataメソッドを呼び出すときは、添付ファイルへ割り当てる必要のあるファイル名を指定する必要があります。The attachData method may be used to attach a raw string of bytes as an attachment. When calling the attachData method, you should provide the filename that should be assigned to the attachment:

/**
 * 通知のメール表現の取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->greeting('Hello!')
                ->attachData($this->pdf, 'name.pdf', [
                    'mime' => 'application/pdf',
                ]);
}

Mailablesの使用Using Mailables

必要に応じ、通知のtoMailメソッドから完全なMailableオブジェクトを返せます。MailMessageの代わりにMaileableを返すときは、Mailableオブジェクトのtoメソッドを使ってメッセージ受信者を指定する必要があります。If needed, you may return a full mailable object[/docs/{{version}}/mail] from your notification's toMail method. When returning a Mailable instead of a MailMessage, you will need to specify the message recipient using the mailable object's to method:

use App\Mail\InvoicePaid as InvoicePaidMailable;

/**
 * 通知のメール表現の入手
 *
 * @param  mixed  $notifiable
 * @return Mailable
 */
public function toMail($notifiable)
{
    return (new InvoicePaidMailable($this->invoice))
                ->to($notifiable->email);
}

Mailablesとオンデマンド通知Mailables & On-Demand Notifications

オンデマンド通知を送信する場合、toMailメソッドに渡される$notifiableインスタンスはIlluminate\Notifications\AnonymousNotifiableインスタンスになります。routeNotificationForメソッドは、オンデマンド通知の送信先のメールアドレスを取得するために使用することができます。If you are sending an on-demand notification[#on-demand-notifications], the $notifiable instance given to the toMail method will be an instance of Illuminate\Notifications\AnonymousNotifiable, which offers a routeNotificationFor method that may be used to retrieve the email address the on-demand notification should be sent to:

use App\Mail\InvoicePaid as InvoicePaidMailable;
use Illuminate\Notifications\AnonymousNotifiable;

/**
 * 通知のメール表現の入手
 *
 * @param  mixed  $notifiable
 * @return Mailable
 */
public function toMail($notifiable)
{
    $address = $notifiable instanceof AnonymousNotifiable
            ? $notifiable->routeNotificationFor('mail')
            : $notifiable->email;

    return (new InvoicePaidMailable($this->invoice))
                ->to($address);
}

メール通知のプレビューPreviewing Mail Notifications

メール通知テンプレートを設計するときは、通常のBladeテンプレートのように、レンダリングしたメールメッセージをブラウザですばやくプレビューできると便利です。このため、Laravelはメール通知によって生成したメールメッセージをルートクロージャまたはコントローラから直接返すことができます。MailMessageが返されると、ブラウザにレンダリングされて表示されるため、実際のメールアドレスに送信しなくてもデザインをすばやくプレビューできます。When designing a mail notification template, it is convenient to quickly preview the rendered mail message in your browser like a typical Blade template. For this reason, Laravel allows you to return any mail message generated by a mail notification directly from a route closure or controller. When a MailMessage is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address:

use App\Invoice;
use App\Notifications\InvoicePaid;

Route::get('/notification', function () {
    $invoice = Invoice::find(1);

    return (new InvoicePaid($invoice))
                ->toMail($invoice->user);
});

Markdownメール通知Markdown Mail Notifications

Markdownメール通知により、事前に構築したテンプレートとメール通知のコンポーネントの利点をMailable中で利用できます。メッセージをMarkdownで記述すると、Laravelは美しいレスポンシブHTMLテンプレートをレンダーすると同時に、自動的に平文テキスト版も生成します。Markdown mail notifications allow you to take advantage of the pre-built templates of mail notifications, while giving you more freedom to write longer, customized messages. Since the messages are written in Markdown, Laravel is able to render beautiful, responsive HTML templates for the messages while also automatically generating a plain-text counterpart.

メッセージ生成Generating The Message

対応するMarkdownテンプレートを指定し、Mailableを生成するには、make:notification Artisanコマンドを--markdownオプション付きで使用します。To generate a notification with a corresponding Markdown template, you may use the --markdown option of the make:notification Artisan command:

php artisan make:notification InvoicePaid --markdown=mail.invoice.paid

他のすべてのメール通知と同様に、Markdownテンプレートを使用する通知では、通知クラスにtoMailメソッドを定義する必要があります。ただし、lineメソッドとactionメソッドを使用して通知を作成する代わりに、markdownメソッドを使用して使用するMarkdownテンプレートの名前を指定します。テンプレートで使用できるようにするデータの配列は、メソッドの2番目の引数として渡します。Like all other mail notifications, notifications that use Markdown templates should define a toMail method on their notification class. However, instead of using the line and action methods to construct the notification, use the markdown method to specify the name of the Markdown template that should be used. An array of data you wish to make available to the template may be passed as the method's second argument:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    $url = url('/invoice/'.$this->invoice->id);

    return (new MailMessage)
                ->subject('Invoice Paid')
                ->markdown('mail.invoice.paid', ['url' => $url]);
}

メッセージ記述Writing The Message

Markdownメール通知ではBladeコンポーネントとMarkdown記法が利用でき、メールメッセージを簡単に構築できると同時に、Laravelが用意している通知コンポーネントも活用できます。Markdown mail notifications use a combination of Blade components and Markdown syntax which allow you to easily construct notifications while leveraging Laravel's pre-crafted notification components:

@component('mail::message')
# 発送のお知らせ

商品が発送されました!

@component('mail::button', ['url' => $url])
注文の確認
@endcomponent

注文の確認<br>
{{ config('app.name') }} 様
@endcomponent

ButtonコンポーネントButton Component

ボタンコンポーネントは、中央寄せに配置したボタンリンクをレンダリングします。コンポーネントは、urlとオプションのcolorの2つの引数を取ります。サポートしている色は、primarygreenredです。通知には、必要なだけボタンコンポーネントを追加できます。The button component renders a centered button link. The component accepts two arguments, a url and an optional color. Supported colors are primary, green, and red. You may add as many button components to a notification as you wish:

@component('mail::button', ['url' => $url, 'color' => 'green'])
注文の確認
@endcomponent

PanelコンポーネントPanel Component

パネルコンポーネントは、メッセージの他の部分とは少し異なった背景色のパネルの中に、指定されたテキストブロックをレンダーします。これにより、指定するテキストに注目を集められます。The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the notification. This allows you to draw attention to a given block of text:

@component('mail::panel')
ここはパネルの内容です。
@endcomponent

TableコンポーネントTable Component

テーブルコンポーネントは、MarkdownテーブルをHTMLテーブルへ変換します。このコンポーネントはMarkdownテーブルを内容として受け入れます。デフォルトのMarkdownテーブルの記法を使った、文字寄せをサポートしています。The table component allows you to transform a Markdown table into an HTML table. The component accepts the Markdown table as its content. Table column alignment is supported using the default Markdown table alignment syntax:

@component('mail::table')
| Laravel       | テーブル      | 例       |
| ------------- |:-------------:| --------:|
| 第2カラムは  | 中央寄せ      | $10      |
| 第3カラムは  | 右寄せ        | $20      |
@endcomponent

コンポーネントカスタマイズCustomizing The Components

自身のアプリケーション向きにカスタマイズできるように、Markdown通知コンポーネントはすべてエクスポートできます。コンポーネントをエクスポートするには、vendor:publish Artisanコマンドを使い、laravel-mailアセットをリソース公開します。You may export all of the Markdown notification components to your own application for customization. To export the components, use the vendor:publish Artisan command to publish the laravel-mail asset tag:

php artisan vendor:publish --tag=laravel-mail

このコマンドにより、resources/views/vendor/mailディレクトリ下にMarkdownメールコンポーネントがリソース公開されます。mailディレクトリ下に、htmltextディレクトリがあります。各ディレクトリは名前が示す形式で、利用できるコンポーネントすべてのレスポンシブなプレゼンテーションを持っています。これらのコンポーネントはお好きなよう、自由にカスタマイズしてください。This command will publish the Markdown mail components to the resources/views/vendor/mail directory. The mail directory will contain an html and a text directory, each containing their respective representations of every available component. You are free to customize these components however you like.

CSSのカスタマイズCustomizing The CSS

コンポーネントをエクスポートすると、resources/views/vendor/mail/html/themesディレクトリに、default.cssファイルが用意されます。このファイル中のCSSをカスタマイズすれば、Markdownメール通知変換後のHTML形式の中に、インラインCSSとして自動的に取り込まれます。After exporting the components, the resources/views/vendor/mail/html/themes directory will contain a default.css file. You may customize the CSS in this file and your styles will automatically be in-lined within the HTML representations of your Markdown notifications.

LaravelのMarkdownコンポーネントの完全に新しいテーマを作成したい場合は、html/themesディレクトリの中にCSSファイルを設置してください。CSSファイルに名前をつけ保存したら、mail設定ファイルのthemeオプションを新しいテーマの名前に更新してください。If you would like to build an entirely new theme for Laravel's Markdown components, you may place a CSS file within the html/themes directory. After naming and saving your CSS file, update the theme option of the mail configuration file to match the name of your new theme.

個別の通知にカスタムテーマを使いたい場合は、通知のメールメッセージを構築する時に、themeメソッドを呼び出してください。themeメソッドの引数は、その通知送信で使用するテーマの名前です。To customize the theme for an individual notification, you may call the theme method while building the notification's mail message. The theme method accepts the name of the theme that should be used when sending the notification:

/**
 * 通知のメールプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->theme('invoice')
                ->subject('Invoice Paid')
                ->markdown('mail.invoice.paid', ['url' => $url]);
}

データベース通知Database Notifications

事前要件Prerequisites

database通知チャンネルは、通知情報をデータベーステーブルに格納します。このテーブルには、通知タイプや通知を説明するJSONデータ構造などの情報が含まれます。The database notification channel stores the notification information in a database table. This table will contain information such as the notification type as well as a JSON data structure that describes the notification.

テーブルにクエリを実行して、アプリケーションのユーザーインターフェイスで通知を表示できます。ただし、その前に、通知を保存しておくデータベーステーブルを作成する必要があります。notifications:tableコマンドを使用して、適切なテーブルスキーマを定義するマイグレーションを生成できます。You can query the table to display the notifications in your application's user interface. But, before you can do that, you will need to create a database table to hold your notifications. You may use the notifications:table command to generate a migration[/docs/{{version}}/migrations] with the proper table schema:

php artisan notifications:table

php artisan migrate

データベース通知のフォーマットFormatting Database Notifications

通知でデータベーステーブルへの保存をサポートする場合、通知クラスにtoDatabasetoArrayメソッドを定義する必要があります。このメソッドは$notifiableエンティティを受け取り、プレーンなPHP配列を返す必要があります。返された配列はJSONへエンコードされ、notificationsテーブルのdataカラムに保存されます。toArrayメソッドの例を見てみましょう。If a notification supports being stored in a database table, you should define a toDatabase or toArray method on the notification class. This method will receive a $notifiable entity and should return a plain PHP array. The returned array will be encoded as JSON and stored in the data column of your notifications table. Let's take a look at an example toArray method:

/**
 * 通知の配列プレゼンテーションの取得
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toArray($notifiable)
{
    return [
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
    ];
}

toDatabasetoArraytoDatabase Vs. toArray

toArrayメソッドはbroadcastチャンネルでも使用され、JavaScriptで駆動するフロントエンドへブロードキャストするデータを決定するため使われます。databaseチャンネルとbroadcastチャンネルに別々な2つの配列表現が必要な場合は、toArrayメソッドの代わりにtoDatabaseメソッドを定義する必要があります。The toArray method is also used by the broadcast channel to determine which data to broadcast to your JavaScript powered frontend. If you would like to have two different array representations for the database and broadcast channels, you should define a toDatabase method instead of a toArray method.

通知へのアクセスAccessing The Notifications

通知をデータベースへ保存したら、notifiableエンティティからアクセスするための便利な方法が必要になるでしょう。LaravelのデフォルトのApp\Models\Userモデルに含まれているIlluminate\Notifications\Notificationトレイトには、エンティティのために通知を返すnotificationsEloquentリレーションが含まれています。通知を取得するため、他のEloquentリレーションと同様にこのメソッドにアクセスできます。デフォルトで通知は「created_at」タイムスタンプで並べ替えられ、コレクションの先頭に最新の通知が表示されます。Once notifications are stored in the database, you need a convenient way to access them from your notifiable entities. The Illuminate\Notifications\Notifiable trait, which is included on Laravel's default App\Models\User model, includes a notifications Eloquent relationship[/docs/{{version}}/eloquent-relationships] that returns the notifications for the entity. To fetch notifications, you may access this method like any other Eloquent relationship. By default, notifications will be sorted by the created_at timestamp with the most recent notifications at the beginning of the collection:

$user = App\Models\User::find(1);

foreach ($user->notifications as $notification) {
    echo $notification->type;
}

「未読」通知のみを取得する場合は、unreadNotificationsリレーションを使用します。この場合も、コレクションの先頭に最新の通知を含むよう、created_atタイムスタンプで並べ替えられます。If you want to retrieve only the "unread" notifications, you may use the unreadNotifications relationship. Again, these notifications will be sorted by the created_at timestamp with the most recent notifications at the beginning of the collection:

$user = App\Models\User::find(1);

foreach ($user->unreadNotifications as $notification) {
    echo $notification->type;
}

lightbulb">Tip!! JavaScriptクライアントから通知にアクセスするには、現在のユーザーなどのnotifiableエンティティの通知を返す、通知コントローラをアプリケーションで定義する必要があります。次に、JavaScriptクライアントからそのコントローラのURLへHTTPリクエストを送信します。{tip} To access your notifications from your JavaScript client, you should define a notification controller for your application which returns the notifications for a notifiable entity, such as the current user. You may then make an HTTP request to that controller's URL from your JavaScript client.

Readとしての通知作成Marking Notifications As Read

通常、ユーザーが閲覧したときに、その通知を「既読」とマークするでしょう。Illuminate\Notifications\Notifiableトレイトは、通知のデータベースレコード上にある、read_atカラムを更新するmarkAsReadメソッドを提供しています。Typically, you will want to mark a notification as "read" when a user views it. The Illuminate\Notifications\Notifiable trait provides a markAsRead method, which updates the read_at column on the notification's database record:

$user = App\Models\User::find(1);

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

各通知をループで処理する代わりに、markAsReadメソッドを通知コレクションへ直接使用できます。However, instead of looping through each notification, you may use the markAsRead method directly on a collection of notifications:

$user->unreadNotifications->markAsRead();

データベースから取得せずに、全通知に既読をマークするため、複数更新クエリを使用することもできます。You may also use a mass-update query to mark all of the notifications as read without retrieving them from the database:

$user = App\Models\User::find(1);

$user->unreadNotifications()->update(['read_at' => now()]);

テーブルエンティティから通知を削除するために、deleteを使うこともできます。You may delete the notifications to remove them from the table entirely:

$user->notifications()->delete();

ブロードキャスト通知Broadcast Notifications

事前要件Prerequisites

通知をブロードキャストする前に、Laravelのイベントブロードキャストサービスを設定して理解しておく必要があります。イベントブロードキャストは、JavaScriptを利用したフロントエンドから送信するサーバサイドのLaravelイベントに対応する方法を提供しています。Before broadcasting notifications, you should configure and be familiar with Laravel's event broadcasting[/docs/{{version}}/broadcasting] services. Event broadcasting provides a way to react to server-side Laravel events from your JavaScript powered frontend.

ブロードキャスト通知のフォーマットFormatting Broadcast Notifications

broadcastチャンネルは、Laravelのイベントブロードキャストサービスを使用して通知をブロードキャストし、JavaScriptを利用したフロントエンドがリアルタイムで通知をキャッチできるようにします。通知でブロードキャストをサポートする場合は、通知クラスでtoBroadcastメソッドを定義します。このメソッドは$notifyエンティティを受け取り、BroadcastMessageインスタンスを返す必要があります。toBroadcastメソッドが存在しない場合は、toArrayメソッドを使用してブロードキャストする必要のあるデータを収集します。返したデータはJSONへエンコードされ、JavaScriptを利用したフロントエンドにブロードキャストされます。toBroadcastメソッドの例を見てみましょう。The broadcast channel broadcasts notifications using Laravel's event broadcasting[/docs/{{version}}/broadcasting] services, allowing your JavaScript powered frontend to catch notifications in realtime. If a notification supports broadcasting, you can define a toBroadcast method on the notification class. This method will receive a $notifiable entity and should return a BroadcastMessage instance. If the toBroadcast method does not exist, the toArray method will be used to gather the data that should be broadcast. The returned data will be encoded as JSON and broadcast to your JavaScript powered frontend. Let's take a look at an example toBroadcast method:

use Illuminate\Notifications\Messages\BroadcastMessage;

/**
 * 通知のブロードキャストプレゼンテーションの取得
 *
 * @param  mixed  $notifiable
 * @return BroadcastMessage
 */
public function toBroadcast($notifiable)
{
    return new BroadcastMessage([
        'invoice_id' => $this->invoice->id,
        'amount' => $this->invoice->amount,
    ]);
}

ブロードキャストキュー設定Broadcast Queue Configuration

すべてのブロードキャスト通知はキューへ投入されます。ブロードキャスト操作に使用されるキューの接続や名前を設定したい場合は、BroadcastMessageonConnectiononQueueメソッドを使用してください。All broadcast notifications are queued for broadcasting. If you would like to configure the queue connection or queue name that is used to queue the broadcast operation, you may use the onConnection and onQueue methods of the BroadcastMessage:

return (new BroadcastMessage($data))
                ->onConnection('sqs')
                ->onQueue('broadcasts');

通知タイプのカスタマイズCustomizing The Notification Type

指定したデータに加えて、すべてのブロードキャスト通知には、通知の完全なクラス名を含むtypeフィールドもあります。通知のtypeをカスタマイズする場合は、通知クラスでbroadcastTypeメソッドを定義します。In addition to the data you specify, all broadcast notifications also have a type field containing the full class name of the notification. If you would like to customize the notification type, you may define a broadcastType method on the notification class:

use Illuminate\Notifications\Messages\BroadcastMessage;

/**
 * ブロードキャストする通知のタイプ
 *
 * @return string
 */
public function broadcastType()
{
    return 'broadcast.message';
}

通知のリッスンListening For Notifications

Notifications will broadcast on a private channel formatted using a {notifiable}.{id} convention. So, if you are sending a notification to an App\Models\User instance with an ID of 1, the notification will be broadcast on the App.Models.User.1 private channel. When using Laravel Echo, you may easily listen for notifications on a channel using the notification method:Notifications will broadcast on a private channel formatted using a {notifiable}.{id} convention. So, if you are sending a notification to an App\Models\User instance with an ID of 1, the notification will be broadcast on the App.Models.User.1 private channel. When using Laravel Echo[/docs/{{version}}/broadcasting#client-side-installation], you may easily listen for notifications on a channel using the notification method:

Echo.private('App.Models.User.'   userId)
    .notification((notification) => {
        console.log(notification.type);
    });

通知チャンネルのカスタマイズCustomizing The Notification Channel

エンティティのブロードキャスト通知がブロードキャストされるチャンネルをカスタマイズする場合は、notifiableエンティティにreceivesBroadcastNotificationsOnメソッドを定義します。If you would like to customize which channel that an entity's broadcast notifications are broadcast on, you may define a receivesBroadcastNotificationsOn method on the notifiable entity:

<?php

namespace App\Models;

use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * ユーザーがブロードキャストされる通知を受け取るチャンネル
     *
     * @return string
     */
    public function receivesBroadcastNotificationsOn()
    {
        return 'users.'.$this->id;
    }
}

SMS通知SMS Notifications

事前要件Prerequisites

LaravelでのSMS通知の送信は、Vonage(旧称Nexmo)を利用しています。Vonage経由で通知を送信する前に、laravel/nexmo-notification-channelnexmo/laravelComposerパッケージをインストールする必要がありますSending SMS notifications in Laravel is powered by Vonage[https://www.vonage.com/] (formerly known as Nexmo). Before you can send notifications via Vonage, you need to install the laravel/nexmo-notification-channel and nexmo/laravel Composer packages

composer require laravel/nexmo-notification-channel nexmo/laravel

nexmo/laravelパッケージは、独自の設定ファイルを持っています。しかし、この設定ファイルを独自のアプリケーションにエクスポートする必要はありません。NEXMO_KEYおよびNEXMO_SECRET環境変数を使用するだけで、Vonageの公開鍵と秘密鍵を設定できます。The nexmo/laravel package includes its own configuration file[https://github.com/Nexmo/nexmo-laravel/blob/master/config/nexmo.php]. However, you are not required to export this configuration file to your own application. You can simply use the NEXMO_KEY and NEXMO_SECRET environment variables to set your Vonage public and secret key.

次に、nexmo設定エントリをconfig/services.php設定ファイルに追加する必要があります。以下の設定例をコピーして開始できます。Next, you will need to add a nexmo configuration entry to your config/services.php configuration file. You may copy the example configuration below to get started:

'nexmo' => [
    'sms_from' => '15556666666',
],

sms_fromオプションは、SMSメッセージの送信元の電話番号です。Vonageコントロールパネルでアプリケーションの電話番号を生成する必要があります。The sms_from option is the phone number that your SMS messages will be sent from. You should generate a phone number for your application in the Vonage control panel.

SMS通知のフォーマットFormatting SMS Notifications

SMSとしての通知をサポートするには、通知クラスにtoNexmoメソッドを定義する必要があります。このメソッドは$notifiableエンティティを受け取り、Illuminate\Notifications\Messages\NexmoMessageインスタンスを返す必要があります。If a notification supports being sent as an SMS, you should define a toNexmo method on the notification class. This method will receive a $notifiable entity and should return an Illuminate\Notifications\Messages\NexmoMessage instance:

/**
 * 通知のVonage/SMS表現を取得
 *
 * @param  mixed  $notifiable
 * @return NexmoMessage
 */
public function toNexmo($notifiable)
{
    return (new NexmoMessage)
                ->content('Your SMS message content');
}

UnicodeコンテンツUnicode Content

SMSメッセージにUnicode文字が含まれる場合は、NexmoMessageインスタンスを作成するときにunicodeメソッドを呼び出す必要があります。If your SMS message will contain unicode characters, you should call the unicode method when constructing the NexmoMessage instance:

/**
 * 通知のVonage/SMS表現を取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\NexmoMessage
 */
public function toNexmo($notifiable)
{
    return (new NexmoMessage)
                ->content('Your unicode message')
                ->unicode();
}

ショートコード通知のフォーマットFormatting Shortcode Notifications

Laravelは、Vonageアカウントで事前定義されたメッセージテンプレートであるショートコード通知の送信もサポートしています。ショートコードSMS通知を送信するには、通知クラスでtoShortcodeメソッドを定義する必要があります。このメソッド内から、通知のタイプ(alert2fa、またはmarketing)と、テンプレートに入力するカスタム値を指定する配列を返してください。Laravel also supports sending shortcode notifications, which are pre-defined message templates in your Vonage account. To send a shortcode SMS notification, you should define a toShortcode method on your notification class. From within this method, you may return an array specifying the type of notification (alert, 2fa, or marketing) as well as the custom values that will populate the template:

/**
 * 通知のVonage/Shortcode表現を取得
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toShortcode($notifiable)
{
    return [
        'type' => 'alert',
        'custom' => [
            'code' => 'ABC123',
        ],
    ];
}

lightbulb">Tip!! SMS通知のルート指定と同様に、通知モデルrouteNotificationForShortcodeメソッドを実装する必要があります。{tip} Like routing SMS Notifications[#routing-sms-notifications], you should implement the routeNotificationForShortcode method on your notifiable model.

発信元電話番号のカスタマイズCustomizing The "From" Number

config/services.phpファイルで指定している電話番号とは別の電話番号から通知を送信したい場合は、NexmoMessageインスタンスでfromメソッドを呼び出すことができます。If you would like to send some notifications from a phone number that is different from the phone number specified in your config/services.php file, you may call the from method on a NexmoMessage instance:

/**
 * 通知のVonage/SMS表現を取得します。
 *
 * @param  mixed  $notifiable
 * @return NexmoMessage
 */
public function toNexmo($notifiable)
{
    return (new NexmoMessage)
                ->content('Your SMS message content')
                ->from('15554443333');
}

クライアントリファレンスの追加Adding a Client Reference

ユーザー、チーム、または顧客ごとのコストを追跡したい場合は、通知に「クライアントリファレンス」を追加することができます。Vonageでは、このクライアントリファレンスを使用してレポートを作成することができますので、特定の顧客のSMS使用状況をよりわかりやすく理解することができます。リライアントリファレンスは、40文字以内の任意の文字列です。If you would like to keep track of costs per user, team, or client, you may add a "client reference" to the notification. Vonage will allow you to generate reports using this client reference so that you can better understand a particular customer's SMS usage. The client reference can be any string up to 40 characters:

/**
 * 通知のVonage/SMS形式の取得
 *
 * @param  mixed  $notifiable
 * @return NexmoMessage
 */
public function toNexmo($notifiable)
{
    return (new NexmoMessage)
                ->clientReference((string) $notifiable->id)
                ->content('Your SMS message content');
}

SMS通知のルート指定Routing SMS Notifications

Vonage通知を適切な電話番号にルーティングするには、通知エンティティでrouteNotificationForNexmoメソッドを定義します。To route Vonage notifications to the proper phone number, define a routeNotificationForNexmo method on your notifiable entity:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
 * @return \Illuminate\Notifications\Message\SlackMessage

    /**
     * Nexmoチャンネルへの通知をルートする
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return string
     */
    public function routeNotificationForNexmo($notification)
    {
        return $this->phone_number;
    }
}

Slack通知Slack Notifications

事前要件Prerequisites

Slackへの通知を送信し始める前に、ComposerによりSlack通知チャンネルをインストールする必要があります。Before you can send notifications via Slack, you must install the Slack notification channel via Composer:

composer require laravel/slack-notification-channel

チーム用のSlackアプリも作成する必要があります。アプリを作成したら、ワークスペースの「受信Webhook」を設定する必要があります。Slackは更にSlack通知のルーティングに使用できるWebhookのURLも提供します。You will also need to create a Slack App[https://api.slack.com/apps?new_app=1] for your team. After creating the App, you should configure an "Incoming Webhook" for the workspace. Slack will then provide you with a webhook URL that you may use when routing Slack notifications[#routing-slack-notifications].

Slack通知のフォーマットFormatting Slack Notifications

通知がSlackメッセージとしての送信をサポートする場合、通知クラスにtoSlackメソッドを定義する必要があります。このメソッドは$notifiableエンティティを受け取り、Illuminate\Notifications\Messages\SlackMessageインスタンスを返す必要があります。Slackメッセージはテキストと同時に、追加テキストのフォーマットか、フィールドの配列を「添付」として含みます。基本的なtoSlackの例を見てください。If a notification supports being sent as a Slack message, you should define a toSlack method on the notification class. This method will receive a $notifiable entity and should return an Illuminate\Notifications\Messages\SlackMessage instance. Slack messages may contain text content as well as an "attachment" that formats additional text or an array of fields. Let's take a look at a basic toSlack example:

/**
 * 通知のSlackプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
                ->content('One of your invoices has been paid!');
}

Slack添付Slack Attachments

Slackメッセージに「添付」を追加することもできます。添付はシンプルなテキストメッセージよりも、リッチなフォーマットのオプションを提供します。以下の例では、アプリケーションで起きた例外についてのエラー通知で、例外についての詳細情報を表示するリンクを含めています。You may also add "attachments" to Slack messages. Attachments provide richer formatting options than simple text messages. In this example, we will send an error notification about an exception that occurred in an application, including a link to view more details about the exception:

/**
 * 通知のSlackプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/exceptions/'.$this->exception->id);

    return (new SlackMessage)
                ->error()
                ->content('Whoops! Something went wrong.')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Exception: File Not Found', $url)
                               ->content('File [background.jpg] was not found.');
                });
}

添付ではさらに、ユーザーに対し表示すべきデータの配列を指定することもできます。簡単によめるよう指定したデータは、テーブルスタイルの形式で表示されます。Attachments also allow you to specify an array of data that should be presented to the user. The given data will be presented in a table-style format for easy reading:

/**
 * 通知のSlackプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/invoices/'.$this->invoice->id);

    return (new SlackMessage)
                ->success()
                ->content('One of your invoices has been paid!')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Invoice 1322', $url)
                               ->fields([
                                    'Title' => 'Server Expenses',
                                    'Amount' => '$1,234',
                                    'Via' => 'American Express',
                                    'Was Overdue' => ':-1:',
                                ]);
                });
}

Markdown添付コンテンツMarkdown Attachment Content

添付フィールドをMarkdownで構成している場合、markdownメソッドでSlackへ指定した添付フィールドがMarkdown形式のテキストであるため、パースしてから表示するように指示します。このメソッドが受け取る値は、pretexttextfieldsです。Slackの添付形式についての詳細は、Slack APIドキュメントをご覧ください。If some of your attachment fields contain Markdown, you may use the markdown method to instruct Slack to parse and display the given attachment fields as Markdown formatted text. The values accepted by this method are: pretext, text, and / or fields. For more information about Slack attachment formatting, check out the Slack API documentation[https://api.slack.com/docs/message-formatting#message_formatting]:

/**
 * 通知のSlackプレゼンテーションを取得
 *
 * @param  mixed  $notifiable
 * @return SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/exceptions/'.$this->exception->id);

    return (new SlackMessage)
                ->error()
                ->content('Whoops! Something went wrong.')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Exception: File Not Found', $url)
                               ->content('File [background.jpg] was *not found*.')
                               ->markdown(['text']);
                });
}

Slack通知のルート指定Routing Slack Notifications

Slack通知を適切なSlackチームとチャンネルにルーティングするには、通知エンティティでrouteNotificationForSlackメソッドを定義します。これは通知の配信先となるWebフックURLを返します。WebフックURLは、Slackチームに「IncomingWebhook」サービスを追加することで生成できます。To route Slack notifications to the proper Slack team and channel, define a routeNotificationForSlack method on your notifiable entity. This should return the webhook URL to which the notification should be delivered. Webhook URLs may be generated by adding an "Incoming Webhook" service to your Slack team:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Slackチャンネルに対する通知をルートする
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return string
     */
    public function routeNotificationForSlack($notification)
    {
        return 'https://hooks.slack.com/services/...';
    }
}

通知のローカライズLocalizing Notifications

Laravelを使用すると、HTTPリクエストの現在のロケール以外のロケールで通知を送信でき、通知をキュー投入する場合でもこのロケールを記憶しています。Laravel allows you to send notifications in a locale other than the HTTP request's current locale, and will even remember this locale if the notification is queued.

このために、Illuminate\Notifications\Notificationクラスは目的の言語を指定するためのlocaleメソッドを提供しています。通知が評価されると、アプリケーションはこのロケールに変更され、評価が完了すると前のロケールに戻ります。To accomplish this, the Illuminate\Notifications\Notification class offers a locale method to set the desired language. The application will change into this locale when the notification is being evaluated and then revert back to the previous locale when evaluation is complete:

$user->notify((new InvoicePaid($invoice))->locale('es'));

通知可能な複数のエンティティをローカライズするのも、Notificationファサードにより可能です。Localization of multiple notifiable entries may also be achieved via the Notification facade:

Notification::locale('es')->send(
    $users, new InvoicePaid($invoice)
);

ユーザー希望のローケルUser Preferred Locales

ユーザーの希望するローケルをアプリケーションで保存しておくことは良くあります。notifiableモデルでHasLocalePreference契約を実装すると、通知送信時にこの保存してあるローケルを使用するように、Laravelへ指示できます。Sometimes, applications store each user's preferred locale. By implementing the HasLocalePreference contract on your notifiable model, you may instruct Laravel to use this stored locale when sending a notification:

use Illuminate\Contracts\Translation\HasLocalePreference;

class User extends Model implements HasLocalePreference
{
    /**
     * ユーザーの希望するローケルの取得
     *
     * @return string
     */
    public function preferredLocale()
    {
        return $this->locale;
    }
}

このインターフェイスを実装すると、そのモデルに対しmailableや通知を送信する時に、Laravelは自動的に好みのローケルを使用します。そのため、このインターフェイスを使用する場合、localeメソッドを呼び出す必要はありません。Once you have implemented the interface, Laravel will automatically use the preferred locale when sending notifications and mailables to the model. Therefore, there is no need to call the locale method when using this interface:

$user->notify(new InvoicePaid($invoice));

通知イベントNotification Events

通知送信前イベントNotification Sending Event

通知を送信するときは、通知システムが Illuminate\Notifications\Events\NotificationSendingイベントを発行します。このイベントは、"notifiable "エンティティと通知インスタンス自体を含んでいます。アプリケーションのEventServiceProviderでこのイベントのリスナを登録できます。When a notification is sending, the Illuminate\Notifications\Events\NotificationSending event[/docs/{{version}}/events] is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may register listeners for this event in your application's EventServiceProvider:

/**
 * アプリケーションにマップするイベントリスナの登録
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Notifications\Events\NotificationSending' => [
        'App\Listeners\CheckNotificationStatus',
    ],
];

NotificationSendingイベントのイベントリスナが、そのhandleメソッドからfalseを返した場合、通知は送信されません。The notification will not be sent if an event listener for the NotificationSending event returns false from its handle method:

use Illuminate\Notifications\Events\NotificationSending;

/**
 * イベントの処理
 *
 * @param  \Illuminate\Notifications\Events\NotificationSending  $event
 * @return void
 */
public function handle(NotificationSending $event)
{
    return false;
}

イベントリスナの中では、イベントのnotifiablenotificationchannelプロパティへアクセスし、通知先や通知自体の詳細を調べられます。Within an event listener, you may access the notifiable, notification, and channel properties on the event to learn more about the notification recipient or the notification itself:

/**
 * イベントの処理
 *
 * @param  \Illuminate\Notifications\Events\NotificationSending  $event
 * @return void
 */
public function handle(NotificationSending $event)
{
    // $event->channel
    // $event->notifiable
    // $event->notification
}

通知送信後イベントNotification Sent Event

通知が送信されると通知システムが、Illuminate\Notifications\Events\NotificationSentイベントを発行します。このイベントは、"notifiable"エンティティと通知インスタンス自体を含んでいます。このイベントのリスナはEventServiceProviderで登録できます。When a notification is sent, the Illuminate\Notifications\Events\NotificationSent event[/docs/{{version}}/events] is dispatched by the notification system. This contains the "notifiable" entity and the notification instance itself. You may register listeners for this event in your EventServiceProvider:

/**
 * アプリケーションにマップされるイベントリスナ
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Notifications\Events\NotificationSent' => [
        'App\Listeners\LogNotification',
    ],
];

lightbulb">Tip!! EventServiceProviderでリスナを登録した後に、event:generate Artisanコマンドを使うと、リスナクラスが素早く生成できます。{tip} After registering listeners in your EventServiceProvider, use the event:generate Artisan command to quickly generate listener classes.

イベントリスナ内では、イベントの notifiablenotificationchannelresponseプロパティにアクセスして、通知先や通知自体の詳細を知ることができます。Within an event listener, you may access the notifiable, notification, channel, and response properties on the event to learn more about the notification recipient or the notification itself:

/**
 * イベントの処理
 *
 * @param  \Illuminate\Notifications\Events\NotificationSent  $event
 * @return void
 */
public function handle(NotificationSent $event)
{
    // $event->channel
    // $event->notifiable
    // $event->notification
    // $event->response
}

カスタムチャンネルCustom Channels

Laravelには通知チャンネルがいくつか付属していますが、他のチャンネルを介して通知を配信する独自​​のドライバを作成することもできます。Laravelではこれをシンプルに実現できます。作成開始するには、sendメソッドを含むクラスを定義します。このメソッドは、$notifying$notificationの2つの引数を受け取る必要があります。Laravel ships with a handful of notification channels, but you may want to write your own drivers to deliver notifications via other channels. Laravel makes it simple. To get started, define a class that contains a send method. The method should receive two arguments: a $notifiable and a $notification.

sendメソッド内で、通知メソッドを呼び出して、チャンネルが理解できるメッセージオブジェクトを取得し、必要に応じて通知を$notifiableインスタンスに送信します。Within the send method, you may call methods on the notification to retrieve a message object understood by your channel and then send the notification to the $notifiable instance however you wish:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Notification;

class VoiceChannel
{
    /**
     * 指定された通知の送信
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        $message = $notification->toVoice($notifiable);

        // 通知を$notifiableインスタンスへ送信する…
    }
}

通知チャンネルクラスを定義したら、任意の通知のviaメソッドからクラス名を返せます。この例では、通知のtoVoiceメソッドは、ボイスメッセージを表すために選択するどんなオブジェクトも返せます。たとえば、次のメッセージを表すために独自のVoiceMessageクラスを定義できます。Once your notification channel class has been defined, you may return the class name from the via method of any of your notifications. In this example, the toVoice method of your notification can return whatever object you choose to represent voice messages. For example, you might define your own VoiceMessage class to represent these messages:

<?php

namespace App\Notifications;

use App\Notifications\Messages\VoiceMessage;
use App\Notifications\VoiceChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
    use Queueable;

    /**
     * 通知チャンネルの取得
     *
     * @param  mixed  $notifiable
     * @return array|string
     */
    public function via($notifiable)
    {
        return [VoiceChannel::class];
    }

    /**
     * 通知の音声プレゼンテーションを取得
     *
     * @param  mixed  $notifiable
     * @return VoiceMessage
     */
    public function toVoice($notifiable)
    {
        // ...
    }
}

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作