rezawikan/custom-notifications

Laravel的自定义通知

dev-master 2019-05-10 01:45 UTC

This package is auto-updated.

Last update: 2024-09-10 14:32:05 UTC


README

用于Laravel中自定义通知(DatabaseChannels)的包。

此包可以帮助您在各种模型和类中改进Laravel的通知。让我们看看如何轻松设置。

安装

您可以通过composer安装此包

composer require rezawikan/custom-notifications

用法

服务提供器将自动注册。或者,您也可以在config/app.php文件中手动添加服务提供器

'providers' => [
    // ...
    Rezawikan\CustomNotifications\CustomNotificationServiceProvider::class,
];

迁移数据库并创建您第一个用于此包的通知。

php artisan migrate
php artisan make:notification NotificationName

在通知中使用自定义数据库通道。如果您想添加其他方法,如邮件或短信,那是可以的。

use Rezawikan\CustomNotifications\Notifications\Channels\DatabaseChannel;

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

    }

自定义通知的表示数组。您可以添加任何内容,根据您在构造方法中接收到的数据。

  • 注意,如果您更改了toArray函数的结构,您可以使用php artisan notifications:restructure重新构建数据库。
/**
    * Get the array representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return array
    */
   public function toArray($notifiable)
   {
       return [
           'comment' => [
             'id'   => $this->comment->id,
             'body' => $this->comment->body
           ]
       ];
   }

现在,转到用户模型。您必须将通知表的关系添加到其中。

use Illuminate\Notifications\Notifiable;
use App\App\Notifications\Models\DatabaseNotification;

class User extends Authenticatable
{
  use Notifiable;
  
  /**
     * [posts description]
     * @return [type] [description]
     */
    public function notifications()
    {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')->orderBy('created_at','desc');
    }
}

然后您可以在控制器或路由中使用它。

  $user = User::find(1);
  $comment = Comment::find(1);

  $user->notify(new CommentCreated($comment));

属性

在$notification对象上存在属性值。在此包中,我们还有额外的值。

$notification->models
$notification->type_class

Blade视图提示

在控制器中生成通知。确保您已登录到您的应用。

$notifications = $request->user()->notifications;

创建插槽Blade,放置在resources/notifications/notification.blade.php中

<div>
{{ $slot }}
Mark as read
</div>

创建组件Blade,放置在resources/notifications/types/name.blade.php中。文件名必须与模型名称一致。在我们的例子中,我们使用了评论模型,您可以添加其他模型。

@component('notifications/notification')
  {{ $notification->data->author->name }} posted comment
@endcomponent

在索引Blade或想要显示通知列表的地方。

@foreach($notifications as $notification)
  @include('notifications/type/'. snake_case($notification->type), compact('notification'))
@endforeach

元数据

Mochammad Rezza Wikandito – @rezawikanreza.wikan.dito@gmail.com

https://github.com/rezawikan/custom-notifications