You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中无需Notifiable实例发送通用通知的实现方案问询

Laravel 无对应模型的管理员通知封装方案

完全可以实现你要的效果,两种常用封装方式如下:

方案1:通知类内置静态发送方法(推荐,无侵入性)

直接在你的SomeLaravelNotification类中新增自定义静态方法,把路由逻辑封装到类内部:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class SomeLaravelNotification extends Notification
{
    use Queueable;

    // 你原有通知类的其他逻辑...

    // 新增管理员发送静态方法
    public static function sendToAdmin()
    {
        \Notification::route('email', 'admin@myapp.example')
            ->notify(new self());
    }
}

调用时不需要再写路由逻辑,直接执行以下代码即可:

SomeLaravelNotification::sendToAdmin();

该方案不需要修改框架底层逻辑,兼容原生通知的所有特性,适配多个管理员、多渠道发送的需求也很容易扩展。

方案2:扩展Notification门面,实现你要求的调用格式

如果你需要严格实现Notification::send(new SomeLaravelNotification());的调用形式,可以扩展原生通知门面的逻辑:

  1. 首先在app/Providers/AppServiceProvider.php的register方法中添加扩展逻辑:
public function register()
{
    $this->app->extend('notification', function ($originalNotification) {
        return new class($originalNotification) {
            protected $original;

            public function __construct($original)
            {
                $this->original = $original;
            }

            public function send($notification, $channels = null)
            {
                // 检测通知类是否配置了管理员接收路由
                if (property_exists($notification, 'adminRecipientRoute')) {
                    $route = $notification->adminRecipientRoute;
                    return $this->original->route($route['channel'], $route['target'])
                        ->notify($notification);
                }

                // 原生发送逻辑兜底
                return $this->original->send(...func_get_args());
            }

            // 透传其他所有方法到原生通知类
            public function __call($method, $parameters)
            {
                return $this->original->$method(...$parameters);
            }
        };
    });
}
  1. 在你的通知类中添加接收路由配置属性:
// 放在SomeLaravelNotification类的属性定义部分
public $adminRecipientRoute = [
    'channel' => 'email',
    'target' => 'admin@myapp.example'
];

配置完成后就可以直接用你要求的方式调用:

Notification::send(new SomeLaravelNotification());

内容的提问来源于stack exchange,提问作者James4645

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:00:02