Friday, March 31, 2017

Trying to hook into Model 'updating' event with a trait

I'm trying to provide a way to track when a user makes a change to a model for a notes section in my application. E.g. John goes and modifies 2 fields, a note would be created saying John has changed title from 'My title 1' to 'My title 2' and content from 'Lipsum' to 'Lipsum2'.

Here is a trait I created:

<?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,
                ];
            }
        });
    }
}

And I am using that trait successfully on my model. However, I'm not sure how to capture the contents of the changes, or if they are even working correctly.

In my controller I have:

$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' => 0 ]);
}

// // Get rid of the CSRF field & method
$data = $request->except([ '_token', '_method' ]);

$site->update($data);

I tried dd($site->changes) before and after $site->update($data); but it just returns null.

What am I doing wrong?



via Mark

Advertisement