Метод error
Метод error класса MailMessage применяется к объекту почтового сообщения и устанавливает стиль оформления как ошибка. Обычно это выражается в красной цветовой гамме, соответствующей иконке или визуальном выделении важного сообщения. Метод не принимает параметров и возвращает тот же объект MailMessage для построения цепочки вызовов.
Синтаксис
<?php
use Illuminate\Notifications\Messages\MailMessage;
$message = (new MailMessage)
->error()
->subject($subject)
->line($message);
?>
Пример
Давайте создадим уведомление об ошибке оплаты в классе Notification:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class PaymentFailedNotification extends Notification
{
use Queueable;
protected $reason;
public function __construct($reason)
{
$this->reason = $reason;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Payment Failed')
->greeting('Hello!')
->line('Your payment could not be processed.')
->line('Reason: ' . $this->reason)
->action('Try Again', url('/payment/retry'))
->line('If you continue to experience issues, please contact support.');
}
}
?>
Результат отправки письма:
<div style="color: #721c24; background-color: #f8d7da; border-color: #f5c6cb;">
<h1>Payment Failed</h1>
<h2>Hello!</h2>
<p>Your payment could not be processed.</p>
<p>Reason: Insufficient funds</p>
<a href="/payment/retry">Try Again</a>
<p>If you continue to experience issues, please contact support.</p>
</div>
Пример
Отправим уведомление об ошибке сервера администратору с деталями проблемы:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class ServerErrorNotification extends Notification
{
use Queueable;
protected $errorCode;
protected $errorMessage;
public function __construct($errorCode, $errorMessage)
{
$this->errorCode = $errorCode;
$this->errorMessage = $errorMessage;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Critical Server Error #' . $this->errorCode)
->greeting('Alert: Server Issue Detected')
->line('A critical error has occurred on the server:')
->line('Error Code: ' . $this->errorCode)
->line('Message: ' . $this->errorMessage)
->line('Time: ' . now()->format('Y-m-d H:i:s'))
->action('View Server Status', url('/admin/status'))
->salutation('System Administrator');
}
}
?>
Результат выполнения кода:
<div style="color: #721c24; background-color: #f8d7da; border-color: #f5c6cb;">
<h1>Critical Server Error #500</h1>
<h2>Alert: Server Issue Detected</h2>
<p>A critical error has occurred on the server:</p>
<p>Error Code: 500</p>
<p>Message: Database connection failed</p>
<p>Time: 2026-09-07 14:30:45</p>
<a href="/admin/status">View Server Status</a>
<p>System Administrator</p>
</div>
Пример
Используем метод error в контроллере для отправки уведомления пользователю о неудачной операции:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notifications\OrderFailedNotification;
use Illuminate\Support\Facades\Notification;
use App\Models\User;
class OrderController extends Controller
{
public function processOrder(Request $request)
{
$orderId = $request->input('order_id');
$userId = $request->input('user_id');
$user = User::find($userId);
$isSuccessful = $this->processPayment($orderId);
if (!$isSuccessful) {
Notification::send($user, new OrderFailedNotification($orderId));
return response()->json(['error' => 'Order processing failed']);
}
return response()->json(['success' => 'Order processed successfully']);
}
private function processPayment($orderId)
{
// payment processing logic
return false;
}
}
?>
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class OrderFailedNotification extends Notification
{
use Queueable;
protected $orderId;
public function __construct($orderId)
{
$this->orderId = $orderId;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Order #' . $this->orderId . ' - Failed')
->greeting('Order Processing Failed')
->line('We could not process your order #' . $this->orderId . '.')
->line('Please check your payment method and try again.')
->action('View Order Status', url('/orders/' . $this->orderId))
->line('Thank you for your understanding.');
}
}
?>
Результат отправки письма пользователю:
<div style="color: #721c24; background-color: #f8d7da; border-color: #f5c6cb;">
<h1>Order #12345 - Failed</h1>
<h2>Order Processing Failed</h2>
<p>We could not process your order #12345.</p>
<p>Please check your payment method and try again.</p>
<a href="/orders/12345">View Order Status</a>
<p>Thank you for your understanding.</p>
</div>
Смотрите также
-
класс
MailMessage,
который используется для построения почтовых сообщений -
метод
success,
который устанавливает стиль успешного выполнения операции -
метод
subject,
который устанавливает тему письма -
метод
action,
который добавляет кнопку с ссылкой в письмо