Метод notify
Метод notify класса User используется для отправки уведомлений
аутентифицированному пользователю. Он является частью трейта
Notifiable, который по умолчанию включен в модель User.
Метод принимает экземпляр класса уведомления и отправляет его через
все каналы, указанные в уведомлении (email, SMS, база данных и др.).
Первый и единственный параметр - объект уведомления.
Синтаксис
<?php
use App\Models\User;
use App\Notifications\UserNotification;
$user = User::find($id);
$user->notify(new UserNotification($data));
?>
Пример
Давайте отправим пользователю уведомление о регистрации через email:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class RegistrationNotification extends Notification
{
use Queueable;
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('Welcome to our website!')
->line('Thank you for registration.')
->action('Visit Site', url('/'))
->line('Best regards!');
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Notifications\RegistrationNotification;
class UserController extends Controller
{
public function register($id)
{
$user = User::find($id);
$user->notify(new RegistrationNotification());
echo "Notification sent successfully";
}
}
?>
Результат выполнения кода:
"Notification sent successfully"
Пример
Отправим уведомление с данными через несколько каналов:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;
class OrderNotification extends Notification
{
use Queueable;
protected $orderData;
public function __construct($orderData)
{
$this->orderData = $orderData;
}
public function via($notifiable)
{
return ['mail', 'database', 'broadcast'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Order Confirmation')
->line('Your order has been confirmed.')
->line('Order number: ' . $this->orderData['id'])
->line('Total: $' . $this->orderData['total']);
}
public function toArray($notifiable)
{
return [
'order_id' => $this->orderData['id'],
'total' => $this->orderData['total'],
'status' => 'confirmed'
];
}
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'order_id' => $this->orderData['id'],
'message' => 'Order confirmed'
]);
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Notifications\OrderNotification;
class OrderController extends Controller
{
public function confirm($userId)
{
$user = User::find($userId);
$orderData = ['id' => 12345, 'total' => 150];
$user->notify(new OrderNotification($orderData));
return response()->json(['status' => 'ok']);
}
}
?>
Результат выполнения кода:
{"status":"ok"}