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

Метод sendNow

Метод sendNow класса Notification позволяет отправить уведомление немедленно, минуя очередь. В отличие от метода send, который ставит уведомление в очередь для фоновой обработки, sendNow выполняет отправку синхронно в текущем процессе. Первым параметром передаётся получатель или массив получателей, вторым - экземпляр класса уведомления.

Синтаксис

<?php use Illuminate\Support\Facades\Notification; Notification::sendNow($notifiable, $notification); ?>

Пример

Давайте создадим класс уведомления и отправим его немедленно одному пользователю:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; class OrderShipped extends Notification implements ShouldQueue { use Queueable; public function via($notifiable) { return ['mail']; } public function toMail($notifiable) { return (new MailMessage) ->line('Your order has been shipped!'); } } ?>
<?php namespace App\Http\Controllers; use App\Models\User; use App\Notifications\OrderShipped; use Illuminate\Support\Facades\Notification; class OrderController extends Controller { public function ship($orderId) { $user = User::find(1); Notification::sendNow($user, new OrderShipped()); return 'Notification sent immediately'; } } ?>

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

"Notification sent immediately"

Пример

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

<?php namespace App\Http\Controllers; use App\Models\User; use App\Notifications\WelcomeMessage; use Illuminate\Support\Facades\Notification; class UserController extends Controller { public function welcomeNewUsers() { $users = User::where('created_at', '>=', now()->subDay())->get(); if ($users->isNotEmpty()) { Notification::sendNow($users, new WelcomeMessage()); echo 'Welcome notifications sent immediately'; } else { echo 'No new users found'; } } } ?>

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

"Welcome notifications sent immediately"

Пример

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

<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; class SecurityAlert extends Notification { protected $message; public function __construct($message) { $this->message = $message; } public function via($notifiable) { return ['mail', 'sms']; } public function toMail($notifiable) { return (new MailMessage) ->subject('Security Alert') ->line($this->message) ->action('View Details', url('/security')); } } ?>
<?php namespace App\Http\Controllers; use App\Models\Admin; use App\Notifications\SecurityAlert; use Illuminate\Support\Facades\Notification; class SecurityController extends Controller { public function alert() { $admins = Admin::where('active', true)->get(); Notification::sendNow($admins, new SecurityAlert('Suspicious activity detected!')); echo 'Security alert sent immediately'; } } ?>

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

"Security alert sent immediately"

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

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