Метод toDatabase
Метод toDatabase используется в классе уведомления для определения данных, которые будут сохранены в таблице уведомлений базы данных. Метод должен возвращать массив данных, который будет преобразован в JSON и сохранён в поле data. Этот метод вызывается автоматически при отправке уведомления через канал database.
Синтаксис
<?php
use IlluminateNotificationsNotification;
class ExampleNotification extends Notification
{
public function toDatabase($notifiable)
{
return [
'key' => 'value',
// другие данные
];
}
}
?>
Пример
Давайте создадим уведомление о новом комментарии и сохраним его в базу данных:
<?php
namespace AppNotifications;
use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use AppModelsComment;
class CommentNotification extends Notification
{
use Queueable;
protected $comment;
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'comment_id' => $this->comment->id,
'comment_author' => $this->comment->author,
'comment_text' => $this->comment->text,
'post_id' => $this->comment->post_id,
'created_at' => now()->toDateTimeString(),
];
}
}
?>
Пример
Теперь отправим уведомление пользователю и получим сохранённые данные:
<?php
namespace AppHttpControllers;
use AppModelsUser;
use AppModelsComment;
use AppNotificationsCommentNotification;
use IlluminateHttpRequest;
class CommentController extends Controller
{
public function store(Request $request)
{
$comment = Comment::create([
'author' => $request->author,
'text' => $request->text,
'post_id' => $request->post_id,
]);
$user = User::find($request->user_id);
$user->notify(new CommentNotification($comment));
$notifications = $user->notifications;
foreach ($notifications as $notification) {
$data = $notification->data;
echo "Comment ID: " . $data['comment_id'] . "\n";
echo "Author: " . $data['comment_author'] . "\n";
}
}
}
?>
Результат выполнения кода:
"Comment ID: 5"
"Author: John Doe"
Пример
Давайте используем метод toDatabase для сохранения данных о заказе в уведомлении:
<?php
namespace AppNotifications;
use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use AppModelsOrder;
class OrderNotification extends Notification
{
use Queueable;
protected $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'order_id' => $this->order->id,
'order_status' => $this->order->status,
'order_total' => $this->order->total,
'user_id' => $this->order->user_id,
'updated_at' => now()->toDateTimeString(),
];
}
}
?>
Пример
Покажем, как получить и отобразить уведомления из базы данных:
<?php
namespace AppHttpControllers;
use AppModelsUser;
use AppModelsOrder;
use AppNotificationsOrderNotification;
class OrderController extends Controller
{
public function show(User $user)
{
$order = Order::where('user_id', $user->id)->first();
$user->notify(new OrderNotification($order));
$res = $user->notifications->map(function ($notification) {
return [
'order_id' => $notification->data['order_id'],
'status' => $notification->data['order_status'],
'total' => $notification->data['order_total'],
];
});
foreach ($res as $item) {
echo "Order #" . $item['order_id'] . "\n";
echo "Status: " . $item['status'] . "\n";
echo "Total: $" . $item['total'] . "\n";
}
}
}
?>
Результат выполнения кода:
"Order #15"
"Status: completed"
"Total: $45.50"
Смотрите также
-
класс
Notification,
который является базовым для создания уведомлений -
метод
send,
который отправляет уведомление получателю -
метод
via,
который определяет каналы доставки уведомления -
метод
toArray,
который преобразует уведомление в массив для API