发布于 2026-01-06 4 阅读
0

创建 Laravel 通知系统

创建 Laravel 通知系统

Laravel之所以流行,一个重要原因是它为常见的开发问题(如身份验证、联系表单、会话、队列、路由和缓存等)提供了可行的解决方案。

在 Laravel 项目中,生成通知是一项常见的需求。本文将介绍如何通过创建一个 Laravel 通知系统来实现这一目标。在这个系统中,每当用户访问页面时,系统都会通过电子邮件向您发送通知。为了进一步提升用户体验,我还将集成 Slack,以便将通知发送到 Slack 频道。

Laravel 的通知系统易于实现,因为它通过为每条通知设置一个单独的类来生成通知。该类定义了如何使用特定渠道通知用户消息。

安装 Laravel 应用程序

为了快速搭建 Laravel 应用,我使用了Cloudways 的Laravel Hosting 服务。只需在 Cloudways 注册,即可免费点击几下安装 Laravel 应用。

主机 Laravel

创建用户表

安装完成后,创建用户表。启动 SSH 终端,并使用主凭据(可在服务器管理选项卡中找到)登录到您的服务器。

Laravel 通知

现在输入以下命令进入应用程序根目录:


cd applications

cd applicationname/public_html

php artisan migrate

Enter fullscreen mode Exit fullscreen mode

用户表已在数据库中创建。

现在我们来添加一些记录,以便系统可以向该用户发送通知。请转到数据库管理器,并在表中添加一条简单的记录。请务必添加有效的电子邮件地址,因为系统会将通知发送到此电子邮件地址。

Laravel 通知

用户模型创建完成后,我们来看一下。请打开app/User.php 文件,其中包含以下代码:


<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

{

   use Notifiable;

   protected $fillable = [

       'name', 'email', 'password',

   ];

   protected $hidden = [

       'password', 'remember_token',

   ];

}
Enter fullscreen mode Exit fullscreen mode

仔细观察,你会发现使用了Notifiable trait。如果你想让你的模型可接收通知,只需在模型中导入`use Illuminate\Notifications\Notifiable; trait` 即可。

请注意,某些通知渠道需要通知对象提供特定信息。例如,邮件渠道需要模型具有“email”属性,以便确定要向哪个电子邮件地址发送通知。

通过电子邮件通知

返回 SSH,进入应用程序根目录并执行以下命令:


php artisan make:notification Newvisit
Enter fullscreen mode Exit fullscreen mode

现在,请转到app/Notifications/Newvisit.php 文件。在该文件中,您会找到以下代码:


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

class Newvisit extends Notification

{

   use Queueable;

   public function __construct()

   {

       //

   }

   public function via($notifiable)

   {

       return ['mail'];

   }

   public function toMail($notifiable)

   {

       return (new MailMessage)

                   ->line('The introduction to the notification.')

                   ->action('Notification Action', url('/'))

                   ->line('Thank you for using our application!');

   }

   public function toArray($notifiable)

   {

       return [

           //

       ];

   }

}
Enter fullscreen mode Exit fullscreen mode

让我们来理解这段代码。首先,它包含构造函数,所有相关的数据都会注入到构造函数中。

public function via($notifiable)

   {

       return ['mail'];

   }
Enter fullscreen mode Exit fullscreen mode

然后,它提供了 `via()` 方法,允许您选择将通知发送到每个实例的通知方式。
接着,它提供了 `toMail()` 方法,该方法返回三个属性。第一个属性是 `line`,用于指定电子邮件的起始正文。第二个属性是 `action`,用于指定按钮名称和按钮跳转到的 URL。最后一个属性是 `line`,用于指定电子邮件的结束段落。以下是一个示例输出:


       ->line('The introduction to the notification.')

       ->action('Notification Action', 'https://laravel.com')

       ->line('Thank you for using our application!');
Enter fullscreen mode Exit fullscreen mode

Laravel 通知

在 Laravel 中通过电子邮件发送通知

请打开routes/web.php 文件,并将以下代码粘贴到该文件中:


<?php

use App\Notifications\Newvisit;

Route::get('/', function () {

$user = App\User::first();

$user->notify(new Newvisit("A new user has visited on your application."));

   return view('welcome');

});
Enter fullscreen mode Exit fullscreen mode

您需要通过`use App\Notifications\Newvisit` 导入通知类;然后在路由函数中,我调用了 User 表中我插入的第一条记录,代码为 `$user = App\User::first();`。接下来,发送通知,我使用了 `notify`函数,并在以下代码行中通过 `Newvisit` 实例发送通知:`$user->notify(new Newvisit("您的应用程序有新用户访问。"));`

现在打开app\Notifications\Newvisit.php 文件,并在其中添加以下代码。


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

class Newvisit extends Notification

{

   use Queueable;

   protected $my_notification; 

   public function __construct($msg)

   {

       $this->my_notification = $msg; 

   }

   public function via($notifiable)

   {

       return ['mail'];

   }

   public function toMail($notifiable)

   {

       return (new MailMessage)

                   ->line('Welcome '.$this->my_notification)

                   ->action('Welcome to Cloudways', url('www.cloudways.com'))

                   ->line('Thank you for using our application!');

   }

   public function toArray($notifiable)

   {

       return [

           //

       ];

   }

}
Enter fullscreen mode Exit fullscreen mode

接下来打开.env文件,设置数据库凭据和邮件发送函数。有关此步骤的详细信息,请参阅Laravel 电子邮件文章。.env文件应如下所示:


DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=zzjudekqvs

DB_USERNAME=zzjudekqvs

DB_PASSWORD=

BROADCAST_DRIVER=log

CACHE_DRIVER=file

SESSION_DRIVER=file

QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1

REDIS_PASSWORD=null

REDIS_PORT=6379

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=saquib.gt@gmail.com

MAIL_PASSWORD=

MAIL_ENCRYPTION=tls

PUSHER_APP_ID=

PUSHER_APP_KEY=

PUSHER_APP_SECRET=
Enter fullscreen mode Exit fullscreen mode

一切准备就绪。请前往 Cloudways 平台的“应用程序”选项卡,然后点击“启动应用程序”按钮。您将收到一封电子邮件通知。

Laravel 通知

Laravel 通知

在 Laravel 中通过 Slack 发送通知

要创建和发送 Slack 通知,您需要通过 Composer 安装 Guzzle。启动 SSH,并在应用程序根目录下运行以下命令:


composer require guzzlehttp/guzzle

php artisan make:notification Newslack
Enter fullscreen mode Exit fullscreen mode

您需要为 Slack 通知创建一个新类。为此,请转到app/Notifications/Newslack.php并粘贴以下代码。


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;

use Illuminate\Notifications\Notification;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Notifications\Messages\MailMessage;

use Illuminate\Notifications\Messages\SlackMessage;

class Newslack extends Notification

{

   use Queueable;

   public function __construct()

   {

       //

   }

   public function via($notifiable)

   {

       return ['slack'];

   }

   public function toSlack($notifiable)

   {

       return (new SlackMessage)

           ->content('A new visitor has visited to your application . $this->user->first(1->name)');

   } 

}
Enter fullscreen mode Exit fullscreen mode

在这里,via() 方法定义了通知的媒介,而 toSlack()方法将通知发送到 Slack。

设置传入 Webhook

现在要接收 Slack 通知,请访问https://{yourteam}.slack.com/apps。选择“传入 Webhook”类型并添加新配置。

Laravel 通知

复制 Webhook URL 并返回您的 Laravel 应用。

您的模型应该实现一个名为routeNotificationForSlack()的方法,该方法返回此 webhook。因此,请转到app/User.php 文件,并在其中添加以下函数。


public function routeNotificationForSlack()

   {

       Return 'your_webhook_url';

   }
Enter fullscreen mode Exit fullscreen mode

现在转到routes/web.php 文件,并添加以下路由。


Route::get('/slack', function () {



$user = App\User::first();



$user->notify(new Newslack());



   echo "A slack notification has been send";



});
Enter fullscreen mode Exit fullscreen mode

现在前往 Cloudways 平台的“应用程序”选项卡,点击“启动应用程序”按钮,并在 URL 中添加 /slack。您将收到如下所示的 Slack 通知:

通知

结语

Laravel 通知系统是一个强大且易于实现的功能,能为项目增添诸多价值。您可以参考此示例,轻松创建自己的通知系统并将其集成到 Laravel 应用中。如有任何疑问,欢迎在下方留言或在 Twitter 上私信我。祝您编码愉快!

文章来源:https://dev.to/rizwan_saquib/creating-a-laravel-notification-system-6mb