Laravel通过通知系统支持多渠道消息发送,使用make:notification创建通知类,并在via方法指定渠道如邮件、数据库;通过模型的notify()或Notification::send()发送通知;数据库通知需生成表存储,可读取未读通知并标记已读;支持自定义渠道和广播,提升系统灵活性与用户体验。

在 Laravel 中,发送系统通知(Notifications)是一个非常灵活且强大的功能。它允许你通过多种渠道(如数据库、邮件、短信、Slack 等)向用户发送通知信息。下面详细介绍如何使用 Laravel 的通知系统。
使用 Artisan 命令可以快速生成一个通知类:
php artisan make:notification OrderShipped该命令会在 app/Notifications 目录下生成一个 OrderShipped.php 文件。通知类中包含一个 toMail、toDatabase 等方法,用于定义不同渠道的通知内容。
例如,定义一个通过邮件和数据库发送订单发货通知:
class OrderShipped extends Notification
{
    use Queueable;
    public function __construct($order)
    {
        $this->order = $order;
    }
    public function via($notifiable)
    {
        return ['mail', 'database'];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('你的订单已发货')
                    ->action('查看订单', url('/orders/'.$this->order->id))
                    ->line('感谢你的支持!');
    }
    public function toDatabase($notifiable)
    {
        return [
            'order_id' => $this->order->id,
            'title' => '订单已发货',
            'message' => '你的订单 '.$this->order->id.' 已发货,请注意查收。'
        ];
    }
}
Laravel 提供了多种方式来发送通知,以下是常用方法:
$user = User::find(1); $user->notify(new OrderShipped($order));
Notification::send($users, new OrderShipped($order));
public function via($notifiable)
{
    return $notifiable->prefers_sms ? ['database', 'sms'] : ['database', 'mail'];
}
若使用数据库渠道,需先创建数据表存储通知:
php artisan notifications:table然后运行迁移:
php artisan migrate通知会存入 notifications 表。你可以像操作普通模型一样读取未读通知:
$unreadNotifications = $user->unreadNotifications;
标记为已读:
$user->unreadNotifications->markAsRead();
除了内置渠道,Laravel 支持自定义通知渠道(如微信、钉钉等),只需实现 Illuminate\Contracts\Broadcasting\ShouldBroadcast 或注册自定义驱动。
你也可以在通知类中添加 toBroadcast 方法以支持广播通知。
基本上就这些。Laravel 的通知系统结构清晰,扩展性强,合理使用能极大提升用户体验。
以上就是laravel如何发送系统通知(Notifications)_Laravel系统通知发送方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号