18

恕我直言,当前在 Laravel 中保存通知的数据库通道的设计非常糟糕:

  • 例如,您不能在项目上使用外键级联来清理已删除项目的通知
  • 在列中搜索自定义属性data(转换为数组)不是最佳的

您将如何DatabaseNotification在供应商包中扩展模型?

我想将列event_id、、question_iduser_id创建通知的用户)等添加到默认的 laravelnotifications表中

您如何覆盖该send函数以包含更多列?

在:

vendor/laravel/framework/src/Illuminate/Notifications/Channels/DatabaseChannel.php

编码:

class DatabaseChannel
{
 /**
  * Send the given notification.
  *
  * @param  mixed  $notifiable
  * @param  \Illuminate\Notifications\Notification  $notification
  * @return \Illuminate\Database\Eloquent\Model
  */
 public function send($notifiable, Notification $notification)
 {
    return $notifiable->routeNotificationFor('database')->create([
        'id' => $notification->id,
        'type' => get_class($notification),

      \\I want to add these
        'user_id' => \Auth::user()->id,
        'event_id' => $notification->type =='event' ? $notification->id : null, 
        'question_id' => $notification->type =='question' ? $notification->id : null,
      \\End adding new columns

        'data' => $this->getData($notifiable, $notification),
        'read_at' => null,
    ]);
 }
}
4

5 回答 5

37

创建自定义通知通道:

首先,在 App\Notifications 中创建一个类,例如:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Notification;

class CustomDbChannel 
{

  public function send($notifiable, Notification $notification)
  {
    $data = $notification->toDatabase($notifiable);

    return $notifiable->routeNotificationFor('database')->create([
        'id' => $notification->id,

        //customize here
        'answer_id' => $data['answer_id'], //<-- comes from toDatabase() Method below
        'user_id'=> \Auth::user()->id,

        'type' => get_class($notification),
        'data' => $data,
        'read_at' => null,
    ]);
  }

}

via二、在Notification类的方法中使用这个通道:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Notification;

use App\Notifications\CustomDbChannel;

class NewAnswerPosted extends Notification
{
  private $answer;

  public function __construct($answer)
  {
    $this->answer = $answer;
  }

  public function via($notifiable)
  {
    return [CustomDbChannel::class]; //<-- important custom Channel defined here
  }

  public function toDatabase($notifiable)
  {
    return [
      'type' => 'some data',
      'title' => 'other data',
      'url' => 'other data',
      'answer_id' => $this->answer->id //<-- send the id here
    ];
  }
}
于 2017-04-27T13:03:09.737 回答
8

创建并使用您自己的Notification模型和Notifiable特征,然后在您的(用户)模型中使用您自己的 Notifiable 特征。

应用程序\Notifiable.php:

namespace App;

use Illuminate\Notifications\Notifiable as BaseNotifiable;

trait Notifiable
{
    use BaseNotifiable;

    /**
     * Get the entity's notifications.
     */
    public function notifications()
    {
        return $this->morphMany(Notification::class, 'notifiable')
                            ->orderBy('created_at', 'desc');
    }
}

应用\通知.php:

namespace App;

use Illuminate\Notifications\DatabaseNotification;

class Notification extends DatabaseNotification
{
    // ...
}

应用\用户.php:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    // ...
}
于 2018-04-17T17:51:14.827 回答
7

@cweiske 响应的示例。

如果您确实需要扩展Illuminate\Notifications\Channels\DatabaseChannel不创建新频道,您可以:

扩展通道:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Channels\DatabaseChannel as BaseDatabaseChannel;
use Illuminate\Notifications\Notification;

class MyDatabaseChannel extends BaseDatabaseChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function send($notifiable, Notification $notification)
    {
        $adminNotificationId = null;
        if (method_exists($notification, 'getAdminNotificationId')) {
            $adminNotificationId = $notification->getAdminNotificationId();
        }

        return $notifiable->routeNotificationFor('database')->create([
            'id' => $notification->id,
            'type' => get_class($notification),
            'data' => $this->getData($notifiable, $notification),

            // ** New custom field **
            'admin_notification_id' => $adminNotificationId,

            'read_at' => null,
        ]);
    }
}

并再次注册Illuminate\Notifications\Channels\DatabaseChannel应用程序容器:

app\Providers\AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            Illuminate\Notifications\Channels\DatabaseChannel::class,
            App\Notifications\MyDatabaseChannel::class
        );
    }
}

现在Illuminate\Notifications\ChannelManager尝试时createDatabaseDriver将返回您注册的数据库驱动程序。

解决此问题的更多选择!

于 2019-06-08T14:13:35.753 回答
4

与“Bassem El Hachem”不同,我想database在方法中保留关键字via()

所以除了 custom DatabaseChannel,我还写了自己的,在方法ChannelManager中返回我自己的。DatabaseChannelcreateDatabaseDriver()

在我的应用程序的ServiceProvider::register()方法中,我覆盖了原始 ChannelManager 类的单例以返回我的自定义管理器。

于 2018-09-28T05:54:55.510 回答
0

我通过自定义通知类解决了类似的问题:

为此操作创建类:

artisan make:notification NewQuestion

在里面:

public function __construct($user,$question)
    {
        $this->user=$user;
        $this->question=$question;
    }


...

    public function toDatabase($notifiable){
        $data=[
            'question'=>$this->(array)$this->question->getAttributes(),
            'user'=>$this->(array)$this->user->getAttributes()
        ];

        return $data;
    }

然后您可以像这样访问视图或控制器中的正确数据:

@if($notification->type=='App\Notifications\UserRegistered')
<a href="{!!route('question.show',$notification->data['question']['id'])!!}">New question from {{$notification->data['user']['name']}}</a>
@endif
于 2017-07-04T14:51:46.120 回答