添加功能到 laravel 通知

Add function to laravel Notification

我有下一个通知class:

class WelcomeNotification extends Notification
{
    use Queueable;

    public function __construct()
    {
        //
    }

    public function via($notifiable)
    {
        return ['database'];
    }

    public function toDatabase($notifiable)
    {
        return [
            //
        ];
    }
}

我想为此添加一些功能。例如:

public function myFunction()
{
    return 'something';
}

但是 $user->notifications->first()->myFunction return 什么都没有

当您调用 notifications() 关系时,结果是使用 DatabaseNotification 模型的多态关系。正确的做法是继承DatabaseNotification,写自定义函数their.

例如创建app/DatabaseNotification/WelcomeNotification.php并继承DatabaseNotification模型.

namespace App\DatabaseNotification;

use Illuminate\Notifications\DatabaseNotification;

class WelcomeNotification extends DatabaseNotification
{

    public function foo() {
        return 'bar';
    }

}

并覆盖使用 Notifiable 特征的 notifications() 函数:

use App\DatabaseNotification\WelcomeNotification;

class User extends Authenticatable
{
    use Notifiable;

    ...

    public function notifications()
    {
        return $this->morphMany(WelcomeNotification::class, 'notifiable')
                            ->orderBy('created_at', 'desc');
    }

    ...

}

现在您可以按如下方式调用自定义函数:

$user->notifications->first()->foo();