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

Метод via

Метод via класса Notification определяет, по каким каналам следует отправлять уведомление. Он вызывается внутри класса уведомления и должен возвращать массив с названиями каналов. Метод получает экземпляр модели, которой адресовано уведомление, в качестве единственного параметра. Это позволяет динамически выбирать каналы в зависимости от пользователя или ситуации.

Синтаксис

<?php use IlluminateNotificationsNotification; class CustomNotification extends Notification { public function via($notifiable) { return ['mail', 'database', 'broadcast']; } } ?>

Пример

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

<?php namespace AppNotifications; use IlluminateBusQueueable; use IlluminateContractsQueueShouldQueue; use IlluminateNotificationsNotification; use IlluminateNotificationsMessagesMailMessage; class OrderNotification extends Notification { use Queueable; public function via($notifiable) { return ['mail', 'database']; } public function toMail($notifiable) { return (new MailMessage) ->line('Your order has been processed.') ->action('View Order', url('/orders')); } public function toArray($notifiable) { return [ 'order_id' => 123, 'message' => 'Order processed', ]; } } ?>

Теперь отправим это уведомление пользователю:

<?php namespace AppHttpControllers; use AppModelsUser; use AppNotificationsOrderNotification; use IlluminateHttpRequest; class OrderController extends Controller { public function process(Request $request) { $user = User::find(1); $user->notify(new OrderNotification()); return response()->json(['message' => 'Notification sent']); } } ?>

В результате уведомление будет отправлено на почту пользователя и сохранено в таблицу notifications.

Пример

Метод via позволяет динамически определять каналы в зависимости от свойств пользователя. Отправим уведомление по почте только администраторам, а всем остальным - в базу данных:

<?php namespace AppNotifications; use IlluminateNotificationsNotification; use IlluminateNotificationsMessagesMailMessage; class StatusNotification extends Notification { public function via($notifiable) { if ($notifiable->is_admin) { return ['mail', 'database']; } return ['database']; } public function toMail($notifiable) { return (new MailMessage) ->line('Status updated successfully.') ->action('Check Status', url('/status')); } public function toArray($notifiable) { return [ 'status' => 'completed', 'timestamp' => now()->toDateTimeString(), ]; } } ?>

Отправим уведомление двум разным пользователям:

<?php namespace AppHttpControllers; use AppModelsUser; use AppNotificationsStatusNotification; use IlluminateHttpRequest; class StatusController extends Controller { public function update(Request $request) { $admin = User::where('is_admin', true)->first(); $user = User::where('is_admin', false)->first(); $admin->notify(new StatusNotification()); $user->notify(new StatusNotification()); return response()->json(['message' => 'Notifications sent']); } } ?>

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

"Admin received mail and database notification" "User received database notification only"

Пример

Используем метод via для отправки уведомлений только по желаемым каналам. Например, если пользователь отключил почтовые уведомления:

<?php namespace AppNotifications; use IlluminateNotificationsNotification; use IlluminateNotificationsMessagesMailMessage; class ReportNotification extends Notification { public function via($notifiable) { $channels = []; if ($notifiable->email_notifications) { $channels[] = 'mail'; } if ($notifiable->sms_notifications) { $channels[] = 'nexmo'; } $channels[] = 'database'; return $channels; } public function toMail($notifiable) { return (new MailMessage) ->line('Your report is ready.') ->action('Download Report', url('/reports')); } public function toArray($notifiable) { return [ 'report_id' => 456, 'date' => now()->toDateString(), 'message' => 'Report generated', ]; } } ?>

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

<?php namespace AppHttpControllers; use AppModelsUser; use AppNotificationsReportNotification; use IlluminateHttpRequest; class ReportController extends Controller { public function generate(Request $request) { $user = User::find(1); $user->notify(new ReportNotification()); return response()->json(['message' => 'Report notification sent']); } } ?>

Результат выполнения кода для пользователя с включенной почтой и SMS:

["Notification sent via: mail", "Notification sent via: nexmo", "Notification sent via: database"]

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

["Notification sent via: database"]

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

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