恕我直言,当前用于在 Laravel 中保存通知的数据库 channel 设计非常糟糕:
data
中搜索自定义属性列(转换为数组)不是最佳的 您将如何扩展
DatabaseNotification
供应商包中的模型?我想添加列
event_id
, question_id
, user_id
(创建通知的用户)等...到默认 Laravel notifications
table 你如何覆盖
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,
]);
}
}
最佳答案
创建自定义通知 channel :
首先,在 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
中使用这个 channel 通知类中的方法:<?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
];
}
}
关于Laravel:自定义或扩展通知 - 数据库模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646085/