Laravel:自定义或扩展通知-数据库模型

aij0ehis  于 2023-03-19  发布在  其他
关注(0)|答案(6)|浏览(175)

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

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

您将如何扩展供应商包中的DatabaseNotification模型?
我想将列event_idquestion_iduser_id(创建通知的用户)等添加到默认的laravel notifications表中
如何覆盖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,
    ]);
 }
}
hkmswyz6

hkmswyz61#

要创建自定义通知通道:

首先,在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,
    ]);
  }

}

其次,在Notification类的via方法中使用此通道:

<?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
    ];
  }
}
h22fl7wq

h22fl7wq2#

创建并使用您自己的Notification模型和Notifiable trait,然后在您的(用户)模型中使用您自己的Notefiable trait。
可应用\可通知.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;

    // ...
}
x7yiwoj4

x7yiwoj43#

@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将返回您注册的数据库驱动程序。
多一个解决这个问题的方案!

pieyvz9o

pieyvz9o4#

与“Bassem El Hachem”不同,我希望在via()方法中保留database关键字。
因此,除了自定义DatabaseChannel之外,我还编写了自己的ChannelManager,它在createDatabaseDriver()方法中返回自己的DatabaseChannel
在我的应用程序的ServiceProvider::register()方法中,我覆盖了原始ChannelManager类的singleton,以返回我的自定义管理器。

6bc51xsx

6bc51xsx5#

通过侦听creating事件,可以在模型级别支持新列。

class Notification extends DatabaseNotification
{
    use SerializeDate;

    protected static function booted(): void
    {
        static::creating(function (Notification $notification) {
            // logic ...
            $notification->new_column = 'value';
        });
    }
dnph8jn4

dnph8jn46#

我通过定制通知类解决了类似的问题:
创建此操作的类:

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

相关问题