【问题标题】:Laravel - catch all eloquent requestsLaravel - 捕捉所有雄辩的请求
【发布时间】:2016-08-07 11:24:29
【问题描述】:

正如我们可以阅读here,我们可以监听 eloquent 事件并在 AppServiceProvider 中使用它。它是这样的:

public function boot()
{
    User::creating(function ($user) {
        Log::create(['message' => 'create method']);
    });

    User::deleting(function ($user) {
        Log::create(['message' => 'delete method']);
    });
}

对于我所有雄辩的模型,我想登录数据库的创建时间和创建者。这意味着我需要复制粘贴这个 sn-p 20 次,并且只更改 User::creating 部分。

有没有一种方法可以让我从所有模型中捕捉到雄辩的事件并做出这样的事情:

public function boot()
{
    AllModels::creating(function ($model) { // <--- something like this here?
        Log::create([
            'message' => 'create method',
            'model' => get_class($model) // <--- and then get the class name
        ]);

    AllModels::deleting(function ($user) {
       /***/
    }

    });
}

【问题讨论】:

    标签: php laravel events eloquent


    【解决方案1】:

    你可以试试这样的:

    $models = ['User', 'Post', 'Comment', ....];
    foreach ($models as $model) {
        $model::creating(....);
        $model::deleting(....);
    }
    

    类似的方法对我有用(不过我使用 DI 而不是外观)。

    我不久前发现并收藏的另一种方法:

    Event::listen(['eloquent.creating: *'], function() {
        ....
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2023-03-11
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多