我已经这样做了(https://laravel.com/docs/5.7/notifications#database-notifications),我运行了迁移,我在通知中创建了一个 toArray() 和一个 toDatabase() 函数,并且通知是正确的但是,通知不会被保存。我的HablameChannel::send()
方法可以发送很多消息,因为一个证书可以有很多电话号码要通知,所以我向他们发送相同的通知。
这是我的频道代码:
<?php
namespace App\Channels;
use App\Models\Message;
use Illuminate\Notifications\Notification;
class HablameChannel
{
/**
* Send the given notification.
* Envía las mensajes de
*
* @param \App\Models\Owner $notifiable
* @param \Illuminate\Notifications\Notification|\App\Notifications\CertificateToExpire $notification
* @return void
*/
public function send($notifiable, $notification)
{
// Se consultan los mensajes de la entidad notificable, en este caso el certificado.
$messages = $notification->toHablame($notifiable);
// Send notification to the $notifiable instance...
$messages->each->send();
}
}
这是我的通知代码:
<?php
namespace App\Notifications;
use App\Channels\HablameChannel;
use App\Models\Certificate;
use App\Models\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class CertificateToExpire extends Notification
{
use Queueable;
/**
* Certificado por el cual se va a notificar que está a punto de caducar.
*
* @var \App\Models\Certificate
*/
protected $certificate;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(Certificate $certificate)
{
$this->certificate = $certificate;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return [HablameChannel::class];
}
/**
* Get the array representation of the notification.
*
* @param \App\Models\Owner $notifiable
* @return array
*/
public function toArray($notifiable)
{
return $this->toHablame($notifiable)->toArray();
}
/**
* Obtiene los mensajes a enviar por Háblame SMS.
*
* @param \App\Models\Owner $notifiable
* @return \Illuminate\Support\Collection|\App\Models\Message[]
*/
public function toHablame($notifiable)
{
$template = setting(
'plantilla_de_vencimiento',
'CDA DEL CESAR de la 44 le recuerda que la Revisión Técnico-Mecánica del vehículo'
. ' de placa {number_plate} está por vencer.'
. ' Visítenos en la CL 44 N 23A - 46. 3205739223'
);
$engine = new \StringTemplate\Engine();
$body = $engine->render($template, [
'number_plate' => $this->certificate->number_plate,
]);
$now = Carbon::now();
return $this->certificate->recipients_to_notify->map(
function (array $recipient) use ($body, $now) {
return $this->certificate->messages()->create([
'receiver_name' => $recipient['receiver_name'],
'to' => $recipient['to'],
'body' => $body,
'reference' => 'Certificados a punto de vencer.',
]);
}
);
}
}
这是我要求通知的代码:
$certificate->owner->notify(new CertificateToExpire($certificate));