vendredi 1 avril 2016

Laravel 5.1 - How to get updates to relationships in static::updating event

I'm trying to create a trait (for models) that would automatically write all changes made to the model in 'adjustments' table. It would save changes in before and after jsons.

This is the code so far (from Laracasts):

trait LoggingTrait
{
    public static function boot()
    {
        parent::boot();

        static::updating(function($action){
            $action->adjustments()->create(
            [
                'user_id' => Auth::id(),
                'before' => json_encode(array_intersect_key($action->getOriginal(), $action->getDirty())),
                'after' => json_encode($action->getDirty())
            ]);
        });
    }

    public function adjustments()
    {
        return $this->morphMany(Adjustment::class, 'adjustable');
    }
}

This is working very well, except it doesn't save changes to related models.

To make it more clear, this is my Action model:

class Action extends Model
{
    use LoggingTrait;

    public function actionTypes()
    {
        return $this->belongsToMany(ActionType::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function spreadingMaterial()
    {
        return $this->belongsTo(SpreadingMaterial::class);
    }
}

The trait logs all the changes made to the actual Action model, but doesn't care for the changes made to the $action->users(), $action->spreadingMaterials() and $action->actionTypes(). How would I get these changes within the static::updating(...) event?

Or if that is not possible, any other idea on how to tackle this problem is more than welcome.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire