laravel - 如何将自定义事件添加到 Laravel 模型

标签 laravel laravel-5 eloquent laravel-events

我有付款模式,想在付款确认后触发自定义事件。

我的型号代码:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $dates = [
        'created_at', 'updated_at', 'confirmed_at',
    ];

    public function confirmed(){
        $this->setAttribute('confirmed_at', now());
        $this->setAttribute('status', 'confirmed');
    }
}

最佳答案

我可以开火 confirmed事件在 Payment->confirmed()方法,像这样:

    public function confirmed(){
        // todo, throw an exception if already confirmed

        $this->setAttribute('confirmed_at', now());
        $this->setAttribute('status', 'confirmed');

        // fire custom event
        $this->fireModelEvent('confirmed');
    }

并将自定义事件注册到 $dispatchesEvents
 protected $dispatchesEvents = [
        'confirmed' =>  \App\Events\Payment\ConfirmedEvent::class
 ];

完毕。\App\Events\Payment\ConfirmedEvent::class事件将在模型 confirmed() 时调用方法被调用。

如果confirmed() 方法被调用两次,它也建议抛出一个异常。

关于laravel - 如何将自定义事件添加到 Laravel 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363375/

相关文章:

Laravel Carbon 以编程方式获取草稿项目

php - Laravel 文件路径

Laravel 社交名流 400 错误请求响应

php - 找不到类 'User'

php - 中间件。最有效的方法

PHP Lumen 在 null 上调用成员函数 connection()

javascript - 在 vue 组件中检索配置和环境变量

php - 如何在 laravel-validation-rules/credit-card 中获取验证消息

php - Laravel 5 composer 安装失败(psysh、php-parser、ext-tokenizer 错误)

laravel - 如何在 Laravel 5.2 中获取单个列的唯一值?