Команда make:notification
Команда make:notification создаёт новый класс уведомления
в папке app/Notifications. Уведомления в Laravel могут
отправляться через разные каналы: email, SMS (через сервисы
вроде Vonage), Slack, базу данных, а также через
веб-интерфейс с использованием браузерных уведомлений.
При создании класса разработчик может определить логику
формирования сообщения для каждого канала.
Синтаксис
php artisan make:notification NotificationName
Обязательным параметром является имя класса уведомления.
Класс будет создан в директории app/Notifications.
Пример
Давайте создадим уведомление для пользователей о выполнении заказа:
php artisan make:notification OrderCompleted
После выполнения команды будет создан файл:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class OrderCompleted extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*/
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toArray(object $notifiable): array
{
return [
//
];
}
}
Пример
Создадим уведомление для отправки в Slack о новом заказе на сайте:
php artisan make:notification NewOrderNotification
Сгенерированный класс можно настроить для работы с несколькими каналами:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
class NewOrderNotification extends Notification
{
use Queueable;
protected $order;
public function __construct($order)
{
$this->order = $order;
}
public function via(object $notifiable): array
{
return ['slack', 'database'];
}
public function toSlack(object $notifiable): SlackMessage
{
return (new SlackMessage)
->content('New order #' . $this->order->id . ' has been placed!');
}
public function toArray(object $notifiable): array
{
return [
'order_id' => $this->order->id,
'amount' => $this->order->amount,
'created_at' => now(),
];
}
}
Пример
Рассмотрим отправку уведомления пользователю
через фасад Notification в контроллере:
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\User;
use App\Notifications\OrderCompleted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
class OrderController extends Controller
{
public function complete(Request $request, $id)
{
$order = Order::findOrFail($id);
$user = User::findOrFail($order->user_id);
$order->update(['status' => 'completed']);
Notification::send($user, new OrderCompleted());
return redirect()->back();
}
}
Результат отправки уведомления пользователю:
"Notification sent successfully"
Пример
Можно также отправить уведомление нескольким пользователям сразу, передав коллекцию:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Notifications\NewOrderNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
class AdminController extends Controller
{
public function notifyAdmins(Request $request)
{
$admins = User::where('role', 'admin')->get();
$order = [
'id' => 1001,
'amount' => 250.00,
];
Notification::send($admins, new NewOrderNotification($order));
return response()->json(['message' => 'Admins notified']);
}
}
В результате все администраторы получат уведомления в Slack и в базе данных:
["Admins notified successfully"]
Смотрите также
-
команда
make:mail,
создаёт классы для отправки email-писем -
команда
make:job,
создаёт классы для фоновых задач -
команда
make:event,
создаёт классы событий -
команда
make:listener,
создаёт классы обработчиков событий