• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

Laravel中如何发送通知

在本文中,我们将探索 Laravel 网络框架中的通知系统Laravel 中的通知系统允许你通过不同的渠道向用户发送通知。今天,我们将讨论如何通过邮件渠道发送通知。

通知基础

应用程序开发过程中,您经常需要通知用户不同的状态变化。出于安全目的,它可以是在订单状态更改时发送电子邮件通知,也可以是发送有关其登录活动的短信。特别是,我们谈论的是简短的消息,只是提供对状态变化的洞察力。

Laravel 已经提供了一个内置功能,可以帮助我们实现类似的功能——通知。事实上,它使向用户发送通知消息变得轻而易举,并成为一种有趣的体验!

这种方法的美妙之处在于它允许您从不同的渠道中选择将发送的通知。让我们快速浏览一下 Laravel 支持的不同通知渠道。

  • 邮件:通知将以电子邮件的形式发送给用户。

  • 短信:顾名思义,用户将在手机上收到短信通知。

  • slack在这种情况下,通知将在 Slack 频道上发送。

  • 数据库如果您希望构建自定义 UI 来显示通知,此选项允许您将通知存储在数据库中。

在不同的通知通道中,我们将在我们将在本教程的过程中开发的示例用例中使用邮件通道。

事实上,这将是一个非常简单的用例,它允许我们应用程序的用户向每个用户发送消息。当用户在收件箱中收到新邮件时,我们会通过向他们发送电子邮件来通知他们此事件。当然,我们会使用 Laravel 的通知功能来做到这一点!

创建自定义通知类

正如我们之前讨论的,我们将设置一个应用程序,允许我们应用程序的用户相互发送消息。另一方面,当用户通过电子邮件收到来自其他用户的新消息时,我们会通知他们。

在本节中,我们将创建需要的必要文件,实现我们正在寻找的用例。

首先,让我们创建一个Message模型来保存用户相互发送的消息。

$php artisan make:model Message --migration

我们还需要向表中添加一些字段,如to,from因此,让我们在运行命令之前更改迁移文件messagemessagesmigrate

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('from', FALSE, TRUE);
            $table->integer('to', FALSE, TRUE);
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('messages');
    }
}

现在,让我们运行在数据库中创建消息表的 migrate 命令。

$php artisan migrate

那应该messages在数据库中创建表。

此外,请确保您首先启用了默认的 Laravel 身份验证系统,以便注册和登录等功能开箱即用。如果你不确定如何做,Laravel文档提供了一个快速的洞察力。

由于 Laravel 中的每个通知都由一个单独的类表示,因此我们需要创建一个自定义通知类来通知用户。让我们使用下面的 artisan 命令来创建一个自定义通知类——NewMessage。

$php artisan make:notification NewMessage

那应该创建app/Notifications/NewMessage.php类,所以让我们用以下内容替换该文件的内容。

<?php
// app/Notifications/NewMessage.php
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;

class NewMessage extends Notification
{
    use Queueable;
    public $fromUser;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->fromUser = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $subject = sprintf('%s: You\'ve got a new message from %s!', config('app.name'), $this->fromUser->name);
        $greeting = sprintf('Hello %s!', $notifiable->name);

        return (new MailMessage)
                    ->subject($subject)
                    ->greeting($greeting)
                    ->salutation('Yours Faithfully')
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

由于我们将使用邮件通道向用户发送通知,因此via相应地配置了该方法。所以这是允许您配置通知的通道类型的方法。

接下来,有toMail一种方法可以让您配置各种电子邮件参数。实际上,该toMail方法应该返回 的实例\Illuminate\Notifications\Messages\MailMessage,并且该类提供了允许您配置电子邮件参数的有用方法。

在各种方法中,该line方法允许您在消息中添加单行。另一方面,有action一种方法允许您在消息中添加号召性用语按钮。

通过这种方式,您可以格式化将发送给用户的消息。这就是您在使用邮件通道发送通知时应该如何配置通知类的方式。

最后,您需要确保根据方法中配置的通道类型实现必要的via方法。例如,如果您使用在数据库中存储通知的数据库通道,则无需配置该toMail方法;相反,您应该实现该toArray方法,该方法对需要存储在数据库中的数据进行格式化。

如何发送通知

在上一节中,我们创建了一个准备发送通知的通知类。在本节中,我们将创建文件来演示如何使用NewMessage通知类实际发送通知。

app/Http/Controllers/NotificationController.php让我们使用以下内容创建一个控制器文件。

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Message;
use App\User;
use App\Notifications\NewMessage;
use Illuminate\Support\Facades\Notification;

class NotificationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        // user 2 sends a message to user 1
        $message = new Message;
        $message->setAttribute('from', 2);
        $message->setAttribute('to', 1);
        $message->setAttribute('message', 'Demo message from user 2 to user 1.');
        $message->save();
        
        $fromUser = User::find(2);
        $toUser = User::find(1);
        
        // send notification using the "user" model, when the user receives new message
        $toUser->notify(new NewMessage($fromUser));
        
        // send notification using the "Notification" facade
        Notification::send($toUser, new NewMessage($fromUser));
    }
}

当然,您需要在routes/web.php文件中添加关联的路由。

Route::get('notify/index', 'NotificationController@index');

Laravel 允许你通过两种方式发送通知:使用通知实体或通知门面。

如果实体模型类利用该Illuminate\Notifications\Notifiable特征,那么您可以notify在该模型上调用该方法。该类App\User实现了该Notifiable特征,因此它成为了可通知实体。另一方面,您也可以使用Illuminate\Support\Facades\NotificationFacade 向用户发送通知。

我们来看看index控制器的方法。

在我们的例子中,我们将在用户收到新消息时通知他们。因此,我们index首先尝试在方法中模仿这种行为。

notify接下来,我们使用对象上的方法通知收件人用户有新消息$toUser,因为它是通知实体。

$toUser->notify(new NewMessage($fromUser));

您可能已经注意到,我们还在方法$fromUser的第一个参数中传递了对象__construct,因为我们希望在消息中包含from用户名。

另一方面,如果您想使用Notification外观来模仿它,使用以下代码段很容易做到这一点。

Notification::send($toUser, new NewMessage($fromUser));

如您所见,我们使用sendNotification 门面的方法向用户发送通知。

继续并在浏览器中打开 URL http://your-laravel-site-domain/notify/index 。如果您尚未登录,您将被重定向到登录屏幕。登录后,您应该会在用户随附的电子邮件地址收到一封通知电子邮件1

您可能想知道,to当我们尚未在任何地方配置地址时,通知系统如何检测地址。在这种情况下,通知系统会尝试email在可通知对象中查找属性。并且App\User对象类已经具有该属性,因为我们使用的是默认的 Laravel 身份验证系统。

但是,如果您想要覆盖此行为并且想要使用电子邮件以外的其他属性,则只需在通知类中定义以下方法。

public function routeNotificationForMail()
{
    return $this->email_address;
}

现在,通知系统应该寻找email_address属性而不是属性email获取to地址。

这就是如何使用 Laravel 中的通知系统。这也将我们带到了本文的结尾!

结论

我们今天经历的是 Laravel 中有用但最少讨论的特性之一——通知。它允许您通过不同的渠道向用户发送通知。

在简单介绍之后,我们实现了一个真实示例,演示了如何通过邮件通道发送通知。事实上,在发送有关应用程序状态更改的短消息的情况下,它真的很方便。


文章目录
  • 通知基础
  • 创建自定义通知类
  • 如何发送通知
  • 结论