小编Mar*_*ark的帖子

尝试使用特征挂钩模型“更新”事件

我试图提供一种方法来跟踪用户何时对我的应用程序中的注释部分的模型进行更改。例如,John 修改了 2 个字段,将创建一条注释,说明 John 已从title“我的标题 1”更改为“我的标题 2”,并content从“Lipsum”更改为“Lipsum2”。

这是我创建的一个特征:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootChangesTrait()
    {
        static::updating(function($model)
        {
            $this->changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $this->changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的模型上成功地使用了这个特性。但是,我不确定如何捕获更改的内容,或者它们是否正常工作。

在我的控制器中我有:

$site = Site::findOrFail($id);

// Catch and cast the is_active checkbox if it's been unselected
if ( ! $request->exists('is_active') )
{
    $request->request->add([ 'is_active' …
Run Code Online (Sandbox Code Playgroud)

model traits laravel eloquent

0
推荐指数
1
解决办法
2454
查看次数

标签 统计

eloquent ×1

laravel ×1

model ×1

traits ×1