notification
- Send Notification
- Use Notifiable Trait
- Use Notification Facade
- Send to the specified channel
- Notification Queue
- On-demand notification
- Email notification
- Formatted email message
- Additional notification formatting options
- Error message
- Custom recipients
- Markdown email notification
- Generate message
- Write message
- Button component
- Panel component
- Table component
- Custom component
- Self Define CSS
- Broadcast notification
- Text message (SMS) notification
- Slack notification Localized Notification
- Notification event
- Custom channel
- Introduction
- Create notification
- Send notification
- Email notification
- Markdown email notification
- Generate message
- ## Write message
- Custom component
- Database notification
- Broadcast Notification
- SMS notification
- Slack Notifications
- Localized Notification
- Notification events
- Custom channel
Message notification
Nexmo), and Slack. Notifications can also be stored in a database for subsequent display on web pages.
Typically, notifications are short, informative messages used to inform users of what is happening in the application. For example, if you are writing an online transaction application, you should send a "bill payment" notification to the user through email and SMS channel classes.
Create notification
A notification in Laravel is a class (usually stored in the app/Notifications
folder) . Don’t worry if you can’t see it, just run the make:notification
command to create it:
php artisan make:notification InvoicePaid
This command will generate a new one in the app/Notifications
directory notification class. This class contains the via
method and one or more message construction methods (such as toMail
or toDatabase
), which convert notifications into corresponding news.
Send Notification
Use Notifiable Trait
Notifications can be passed Sent in two ways: the notify
method of the Notifiable
trait or the Notification
facade. First let's discuss using the trait:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable{ use Notifiable; }
The default App\User
model uses this trait, which contains a method that can be used to send notifications: notify
. notify
The method requires a notification instance as parameter:
use App\Notifications\InvoicePaid; $user->notify(new InvoicePaid($invoice));
{tip} Remember, you can use the
Illuminate\Notifications\Notifiable
trait in any model , not just in theUser
model.
Using the Notification Facade
In addition, you can send notifications through the Notification
facade. It is mainly used when you send notifications to multiple entities that can receive notifications, such as sending notifications to a collection of users. If you use Facade to send notifications, you must pass the instance that can receive notifications and notifications to the send
method:
Notification::send($users, new InvoicePaid($invoice));
Send the specified channel
Each notification class will have a via
method, which determines the channel on which the notification will be sent. The channels available out of the box are mail
, database
, broadcast
, nexmo
and slack
.
{tip} If you want to use other channels, such as Telegram or Pusher, you can check out the community-driven Laravel Notification Channels website. The
via
method receives a $notifiable
instance. This instance will be the instance of the class that the notification is actually sent to. You can use $notifiable
to decide which channels to use for sending notifications:
/** * 获取通知发送频道。 * * @param mixed $notifiable * @return array */ public function via($notifiable){ return $notifiable->prefers_sms ? ['nexmo'] : ['mail', 'database']; }
Notification Queue
{Note:} Before using the notification queue, you need to configure the queue and start a queue task.
Sending notifications can be time-consuming, especially if channels require additional API calls to transmit notifications. In order to speed up the response time of the application, notifications can be pushed to the queue and sent asynchronously. To implement push notifications to the queue, the corresponding notification class can implement the ShouldQueue
interface and use the Queueable
trait. If the notification class is generated through the make:notification
command, then the interface and trait have been imported by default, and you can quickly add them to the notification class:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; class InvoicePaid extends Notification implements ShouldQueue{ use Queueable; // ... }
ShouldQueue
After the interface is added to the notification class, you can send notifications normally as before. Laravel will automatically detect the ShouldQueue
interface and push the notification to the queue:
$user->notify(new InvoicePaid($invoice));
If you want to delay To send notifications, you can add delay
method after the notification instance:
$when = now()->addMinutes(10); $user->notify((new InvoicePaid($invoice))->delay($when);
On-demand notification
Sometimes You may need to send a notification to a user, but the user does not exist in the application's user system. To achieve this, we use the Notification::route
method to specify a special notification route before sending the notification. :
Notification::route('mail', 'taylor@example.com') ->route('nexmo', '5555555555') ->notify(new InvoicePaid($invoice));
Email notification
##Formatted email message If the notification supports sending by email, you need to define atoMail method on the notification class. This method receives a
$notifiable entity and returns an
Illuminate\Notifications\Messages\MailMessage instance. Mail messages can contain multiple lines of text as well as calls to actions, let's look at an example of the
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('One of your invoices has been paid!') ->action('View Invoice', $url) ->line('Thank you for using our application!'); }
{Note:} Notice that we areIn this example, we register a greeting, a line of text, a call to an action, and another line of text.
$this->invoice->id
is used in the toMailmethod. You can pass any data required for the notification to generate a message to the notification's constructor.
MailMessage These methods provided by the object make formatting short transactional emails quick and easy.
mail Channels convert message components into beautiful, responsive HTML email templates with plain text copy. Here is an example of an email generated through the
mail channel:
{Note:} When sending email notification, make sure that
name
is set in the configuration fileconfig/app.php
value, which will be used in the header and trailer of the email notification message.
Other notification formatting options
In addition to defining multi-line text in the notification class, you can also use the view
method to specify a custom , a template for rendering notification emails:
/** * 获取通知邮件。 * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable){ return (new MailMessage)->view( 'emails.name', ['invoice' => $this->invoice] ); }
Additionally, you can return a mailable object from the toMail
method:
use App\Mail\InvoicePaid as Mailable; /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return Mailable */ public function toMail($notifiable){ return (new Mailable($this->invoice))->to($this->user->email); }
Error Message
Some notifications will inform users of error messages, such as failed order payments. You can call the error
method when constructing the message to indicate that the email message represents error information. When using the error
method in an email message, the action button will turn red:
/** * 获取通知邮件。 * * @param mixed $notifiable * @return \Illuminate\Notifications\Message */ public function toMail($notifiable){ return (new MailMessage) ->error() ->subject('Notification Subject') ->line('...'); }
Custom Recipient
When sending a notification through the mail
channel, the notification system will automatically look for the email
attribute on the notified entity. You can define a routeNotificationForMail
on the entity. To customize which email address to use to send notifications:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable{ use Notifiable; /** * 邮件通道通知的路由。 * * @param \Illuminate\Notifications\Notification $notification * @return string */ public function routeNotificationForMail($notification) { return $this->email_address; } }
Customize the subject
By default, the subject of the email is in the format of "Title style ” notification class name, therefore, if the notification class is named InvoicePaid
, the subject of the email is Invoice Paid
. If you want to specify an explicit subject for the message, you can build the message When calling the subject
method:
/** * 获取通知的邮件表示。 * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable){ return (new MailMessage) ->subject('Notification Subject') ->line('...'); }
Custom template
You can publish the resources of the notification extension package. Modify the HTML and plain text templates used for email notifications. After running the following command, the email notification template will be stored in the resources/views/vendor/notifications
directory:
php artisan vendor:publish --tag=laravel-notifications
Markdown Email Notifications
Markdown Email notifications allow you to take advantage of pre-built templates for email notifications, giving you the freedom to write longer, more personalized messages. Because these messages are written in Markdown format, Laravel can also render them into beautiful, responsive HTML templates while automatically generating plain text copies.
Generate message
To generate a notification with the corresponding Markdown template, you can use the Artisan command make:notification
Bring the --markdown
option:
php artisan make:notification InvoicePaid --markdown=mail.invoice.paid
Like other email notifications, notification classes using Markdown templates must also define a toMail
method. However, you can use the markdown
method instead of the line
and action
methods of the constructor notification to specify the Markdown template name to use:
/** * 获取通知的邮件表示。 * * @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 Message
Markdown email notification uses the Blade component and Markdown syntax, allowing you to easily build notifications without breaking away from Laravel's preset components:
@component('mail::message') # Invoice PaidYour invoice has been paid! @component('mail::button', ['url' => $url]) View Invoice @endcomponent Thanks,<br> {{ config('app.name') }} @endcomponent
Button Component
The button component renders a centered button link. This component receives two parameters, url
and optional color
. The supported colors are blue
, green
and red
. You can add any number of button components to the message:
@component('mail::button', ['url' => $url, 'color' => 'green']) View Invoice @endcomponent
Panel component
The panel component renders the given text block into a panel with a light background color and Surrounding messages are distinguished. Suitable for blocks of text that require attention:
@component('mail::panel') This is the panel content. @endcomponent
Table component
The Table component allows you to convert a Markdown table into an HTML table. This component receives a Markdown table as its content. Table column alignment supports using the default Markdown table column alignment syntax:
@component('mail::table') | Laravel | Table | Example | | ------------- |:-------------:| --------:| | Col 2 is | Centered | | | Col 3 is | Right-Aligned | | @endcomponent
Custom component
You can export all Markdown notification components to the application To customize, to export the component, use the Artisan command vendor:publish
to publish laravel-mail
Resource tag:
php artisan vendor:publish --tag=laravel-mail
This command will publish the Markdown email notification component Go to the resources/views/vendor/mail
directory. The mail
directory contains the html
and markdown
directories, each of which contains all of its valid components. You are free to edit these components to your liking.
Custom CSS
After exporting the component, the resources/views/vendor/mail/html/themes
directory will contain a default default.css
file, you can customize the CSS in this file, so that the HTML style of the Markdown notification will be automatically adjusted.
{Note:} If you want to build a completely new theme for the Markdown component, just write a new CSS file in the
html/themes
directory and modifyThe
themeoption of the mail
configuration file is enough.
Database notification
##Preliminary knowledgedatabase Notification channels store notification information in a data table that contains information such as the notification type and custom JSON data describing the notification.
notifications:table command to generate migrations. The file is then used to generate the corresponding data table:
php artisan notifications:table php artisan migrate
Format database notification
If the notification supports saving to the database table, the notification class needs to define the toDatabase
or toArray
method. This method accepts a $notifiable
entity as parameter and returns a native PHP array. The returned data will be encoded as JSON and stored into the data
column of the notifications
table. Let’s look at an example of the toArray
method:
/** * 获取通知的数组表示。 * * @param mixed $notifiable * @return array */ public function toArray($notifiable){ return [ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]; }
toDatabase
Vs. toArray
toArray
method You can also use the broadcast
channel to determine which data is broadcast to the JavaScript client. If you have two different array representations for the database
and broadcast
channels, you need to define the toDatabase
method instead of the toArray
method.
Accessing Notifications
Once notifications are stored in the database, appropriate methods are needed to access them from the notifying entity. The default App\User
model included with Lareval has the Illuminate\Notifications\Notifiable
trait, and its notifications
Eloquent associated methods can return entity notifications. To get notifications, you can access this method like other Eloquent related methods. By default, notifications are sorted by created_at
timestamp:
$user = App\User::find(1); foreach ($user->notifications as $notification) { echo $notification->type; }
To get only "unread" notifications, you can use the unreadNotifications
association method. Again these notifications are sorted by created_at
timestamp:
$user = App\User::find(1); foreach ($user->unreadNotifications as $notification) { echo $notification->type; }
{tip} To access notifications from a JavaScript client, you need to define a notification controller for your application that returns a notification Notifications for entities, such as the current user. HTTP requests can be sent to this controller URI from a JavaScript client.
Mark notification as read
Typically, after a user reads a notification, you want to mark it as "read" ”. The Illuminate\Notifications\Notifiable
trait provides the markAsRead
method, which updates the read_at
column of the notification record in the database:
$user = App\User::find(1); foreach ($user->unreadNotifications as $notification) { $notification->markAsRead(); }
can be used in the notification control Use the markAsRead
method directly on the collection instead of circularly calling notifications:
$user->unreadNotifications->markAsRead();
You can also use finger updates to mark all notifications as read without reading them from the database:
$user = App\User::find(1); $user->unreadNotifications()->update(['read_at' => now()]);
You can use the delete
method to delete the entire notification from the table:
$user->notifications()->delete();
Broadcast notification
Preliminary knowledge
Before broadcasting notifications, you need to configure and be familiar with Laravel's event broadcast service. Event broadcasting provides a way for the JavaScript client to respond to Laravel events triggered by the server.
Formatted broadcast notifications
broadcast
Channels broadcast notifications using Laravel's event broadcasting service, which allows JavaScript clients to capture notifications in real time. If the notification supports broadcasting, you need to define the toBroadcast
method on the notification class. This method accepts a $notifiable
entity as a parameter and returns a BroadcastMessage
instance. The returned data will be encoded as JSON and broadcast to the JavaScript client. Let's take a look at a toBroadcast
method example
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
All broadcast notifications are put into the broadcast queue. To configure the queue connection or queue name for broadcast operations, you need to use the onConnection
and onQueue
methods of BroadcastMessage
:
return (new BroadcastMessage($data)) ->onConnection('sqs') ->onQueue('broadcasts');
{tip} In addition to the specified data, broadcast notifications also contain the
type
field, which contains the class name of the notification class.
Listening notifications
Notifications will be formatted as {notifiable}.{id}
Forms are broadcast on a private channel, so if you want to send a notification to the App\User
instance with ID 1
, the notification will be on the private channel App.User .1
to broadcast, if you use Laravel Echo, you can use the helper function notification
to easily monitor notifications on a channel:
Echo.private('App.User.' + userId) .notification((notification) => { console.log(notification.type); });
Custom notification channel
If you want to customize the notified entity to receive broadcast notifications on a certain channel, you can define a receivesBroadcastNotificationsOn
method on the notified entity:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable{ use Notifiable; /** * 用户接收广播通知的通道。 * * @return string */ public function receivesBroadcastNotificationsOn() { return 'users.'.$this->id; } }
Text message (SMS) notification
Preliminary knowledge
Laravel sends SMS notification based on Nexmo, Before using Nexmo to send notifications, you need to install the corresponding Composer dependency package laravel/nexmo-notification-channel
:
composer require laravel/nexmo-notification-channel
Next step, you need to configure the configuration file config/services.php
Configure accordingly. You can refer to the following sample configuration:
'nexmo' => [ 'key' => env('NEXMO_KEY'), 'secret' => env('NEXMO_SECRET'), 'sms_from' => '15556666666', ],
sms_from
The configuration item is the mobile phone number you use to send SMS messages. You need to generate a mobile phone number for the application in the Nexmo control panel.
Format SMS notification
If the notification supports sending by SMS, then you need to define a toNexmo# on the notification class ## method. This method receives a
$notifiable entity and returns
Illuminate\Notifications\Messages\NexmoMessage instance:
/** * Get the Nexmo / SMS representation of the notification. * * @param mixed $notifiable * @return NexmoMessage */ public function toNexmo($notifiable){ return (new NexmoMessage) ->content('Your SMS message content'); }Unicode content If your SMS message Contains Unicode characters, you need to call the
unicode method when constructing the
NexmoMessage instance:
/** * Get the Nexmo / SMS representation of the notification. * * @param mixed $notifiable * @return NexmoMessage */ public function toNexmo($notifiable){ return (new NexmoMessage) ->content('Your unicode message') ->unicode(); }
## If you want to send notifications through a different number than the mobile phone number specified in the configuration file Use Before sending notifications through Slack, the Slack notification channel must be installed through Composer: In addition , you also need to configure an "Incoming Webhook" integration for the Slack group. This integration provides a URL when you Slack notification routing. If notifications support sending via Slack messages, you need to define a Customize the "send" number
config/services.php
, you can use
from method on NexmoMessage
instance: /**
* Get the Nexmo / SMS representation of the notification.
*
* @param mixed $notifiable
* @return NexmoMessage
*/
public function toNexmo($notifiable){
return (new NexmoMessage)
->content('Your SMS message content')
->from('15554443333');
}
SMS notification routing
nexmo
When the channel sends a notification, the notification system will automatically search for the phone_number
attribute on the notified entity. If you want to customize the mobile number to which notifications are sent, you can define a routeNotificationForNexmo
method on this entity: <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable{
use Notifiable;
/**
* Route notifications for the Nexmo channel.
*
* @param \Illuminate\Notifications\Notification $notification
* @return string
*/
public function routeNotificationForNexmo($notification)
{
return $this->phone;
}
}
Slack Notifications
Preliminary knowledge
composer require laravel/slack-notification-channel
Formatting Slack notifications
toSlack## on the notification class # Method that receives a
$notifiable entity and returns an
Illuminate\Notifications\Messages\SlackMessage instance containing the text content and "attachments" of formatted extra text or array fields . Let’s look at a basic
toSlack usage example:
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable){
return (new SlackMessage)
->content('One of your invoices has been paid!');
}
from and
to methods And the receiver, the
from method receives a username and emoji identification, while the
to method receives a channel or username:
/** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return SlackMessage */ public function toSlack($notifiable){ return (new SlackMessage) ->from('Ghost', ':ghost:') ->to('#other') ->content('This will be sent to #other'); }You can also use a picture as a logo to replace emoji:
/** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return SlackMessage */ public function toSlack($notifiable){ return (new SlackMessage) ->from('Laravel') ->image('https://laravel.com/favicon.png') ->content('This will display the Laravel logo next to the message'); }Slack AttachmentsYou can also add "attachments" to Slack messages. Compared with simple text messages, attachments can provide richer format choices. In this example, we will send a notification of an exception error that occurred in the application, including a link to view more exception details:
/** * Get the Slack representation of the notification. * * @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.'); }); }The above code will generate the following Slack message:
Attachments also allow you to specify array data to be presented to the user. To improve readability, the given array will be displayed in tabular form:
/** * Get the Slack representation of the notification. * * @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' => ',234', 'Via' => 'American Express', 'Was Overdue' => ':-1:', ]); }); }
The above code will generate the following Slack message:
Markdown attachment content
If some attachment fields contain Markdown, you can use the markdown
method to build Slack to parse and display the attachment fields written in Markdown format. The values supported by this method Include pretext
, text
, or fields
. For more information about Slack formatting, check out the Slack API documentation:
/** * Get the Slack representation of the notification. * * @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 Notification RoutingTo route Slack notifications to the appropriate location, you need to define a
routeNotificationForSlack method on the notified entity, which will return the Webhook URL to which the notification is sent. Webhook URLs can be generated by adding an "Incoming Webhook" service on a Slack group:
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable{ use Notifiable; /** * Route notifications for the Slack channel. * * @param \Illuminate\Notifications\Notification $notification * @return string */ public function routeNotificationForSlack($notification) { return 'https://hooks.slack.com/services/...'; } }Localized notificationsLaravel allows you to Notifications are sent in a language other than the current locale, and that locale is remembered when notifying the queue. To achieve this, the
Illuminate\Notifications\Notification class provides a
locale method to set the desired language. When formatting notifications, the application will change to this language setting, then revert to the previous language setting after formatting is complete:
$user->notify((new InvoicePaid($invoice))->locale('es'));Localization of multiple notifications is also available via
Notification Facade implementation:
Notification::locale('es')->send($users, new InvoicePaid($invoice));User preferred localeIn some cases, the application saves the preferred locale for each user. By implementing the
HasLocalePreference contract on your model, you can specify that Laravel uses the user's saved preferred language setting when sending notifications: Automatically uses the preferred locale. Therefore, there is no need to call the
locale
use Illuminate\Contracts\Translation\HasLocalePreference; class User extends Model implements HasLocalePreference{ /** * Get the user's preferred locale. * * @return string */ public function preferredLocale() { return $this->locale; } }
When the notification is sent , the notification system will trigger the Illuminate\Notifications\Events\NotificationSent
event. This event instance contains the notified entity (such as the user) and the notification instance itself. You can register a listener for this event inEventServiceProvider:
$user->notify(new InvoicePaid($invoice));
{Tip} After registering a listener in EventServiceProvider, use the Artisan command,event:generate
notifiablecan quickly generate listener classes.
In an event listener, you can access the
notification and
channel properties of the event to learn about the notification recipients and the notification itself. More information on:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Notifications\Events\NotificationSent' => [ 'App\Listeners\LogNotification', ], ];
Laravel provides us with multiple notification channels, but try to write a custom channel driver It's also easy to send notifications through other channels. First define a class containing the send
method, which receives two parameters:$notifiable and
$notification:
/** * Handle the event. * * @param NotificationSent $event * @return void */ public function handle(NotificationSent $event){ // $event->channel // $event->notifiable // $event->notification // $event->response }
Once the notification channel class is defined, the class name can be returned in the application through the via
method:
<?php namespace App\Channels; 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); // Send notification to the $notifiable instance... } }