РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
839 of 1392 menu

Метод toArray

Метод toArray класса Notification определяет, какие данные будут сохранены в базе данных или переданы через broadcast-каналы. Он должен возвращать ассоциативный массив, содержащий всю необходимую информацию об уведомлении. Этот метод является обязательным для реализации, если вы используете каналы database или broadcast.

Синтаксис

<?php namespace AppNotifications; use IlluminateNotificationsNotification; class CustomNotification extends Notification { public function toArray($notifiable) { return [ 'key' => 'value', // другие данные ]; } } ?>

Метод принимает один параметр - $notifiable - экземпляр модели, которой отправляется уведомление. Возвращаемое значение должно быть массивом с данными уведомления.

Пример

Давайте создадим уведомление о новом комментарии, которое будет сохраняться в базу данных:

<?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', 'mail']; } public function toArray($notifiable) { return [ 'comment_id' => $this->comment->id, 'comment_text' => $this->comment->text, 'user_id' => $this->comment->user_id, 'post_id' => $this->comment->post_id, 'created_at' => $this->comment->created_at->format('Y-m-d H:i:s'), ]; } public function toMail($notifiable) { // содержимое для email } } ?>

Пример

Отправим уведомление пользователю и получим данные из базы данных:

<?php namespace AppHttpControllers; use AppModelsUser; use AppNotificationsCommentNotification; class NotificationController extends Controller { public function send() { $user = User::find(1); $comment = Comment::find(5); $user->notify(new CommentNotification($comment)); $notifications = $user->notifications; foreach ($notifications as $notification) { $data = $notification->data; echo "Comment ID: " . $data['comment_id']; echo "Comment text: " . $data['comment_text']; } } } ?>

Результат выполнения кода:

"Comment ID: 5" "Comment text: Great article!"

Пример

Используем метод toArray для broadcast-канала, чтобы передать данные через WebSocket:

<?php namespace AppNotifications; use IlluminateNotificationsNotification; use IlluminateNotificationsMessagesBroadcastMessage; class StatusUpdateNotification extends Notification { protected $status; protected $message; public function __construct($status, $message) { $this->status = $status; $this->message = $message; } public function via($notifiable) { return ['broadcast', 'database']; } public function toArray($notifiable) { return [ 'status' => $this->status, 'message' => $this->message, 'timestamp' => now()->toDateTimeString(), 'user_id' => $notifiable->id, 'user_name' => $notifiable->name, ]; } public function toBroadcast($notifiable) { return (new BroadcastMessage($this->toArray($notifiable))) ->onConnection('sync'); } } ?>

Пример

Отправим broadcast-уведомление и проверим структуру данных:

<?php namespace AppHttpControllers; use AppModelsUser; use AppNotificationsStatusUpdateNotification; class BroadcastController extends Controller { public function updateStatus() { $user = User::find(2); $status = 'active'; $message = 'User status updated'; $notification = new StatusUpdateNotification($status, $message); $user->notify($notification); $data = $notification->toArray($user); foreach ($data as $key => $value) { echo $key . ': ' . $value; } } } ?>

Результат выполнения кода:

"status: active" "message: User status updated" "timestamp: 2026-09-07 14:30:25" "user_id: 2" "user_name: John Doe"

Смотрите также

  • метод toMail,
    который формирует email-представление уведомления
  • метод toDatabase,
    который определяет данные для сохранения в базе данных
  • метод toBroadcast,
    который формирует broadcast-сообщение
  • метод notify,
    который отправляет уведомление модели
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить