2

I have a need to update a field in a database table to an MD5 hash of of the other field values (sting concat)

I am trying to do this via the eloquent model saving/updating/creating events but it appears that you cannot use the events to update/alter data.

Currently i have the following:

static::saving(function ($model) {
        CustomLog::debug(__CLASS__, __FUNCTION__, __LINE__, 'saving fired');
        $model->sku = static::generateSku($model);
    });

This is not having the desired affect; is there a way to do this - I dont want to have to add a manual call to this function in various places as i feel it should be automatic.

Thanks in advance

Scott-David Jones
  • 292
  • 1
  • 6
  • 22

2 Answers2

2

So i think i have the answer here. it is two folds:

  1. in the event callback you need to update the field in question using the $model->setAttribute($field, $value); function.
  2. in my generateSku function i was relying on the models relationships to get names etc from child relationships; however on the even the models relationships had not updated at this time, thus the function was using old relationships. Changing this to use the data from the model/table that was being updated rather than its relationships had the desired effect.

All in all the event code now looks like this:

static::saving(function ($model) {
        CustomLog::debug(__CLASS__, __FUNCTION__, __LINE__, 'saving model fired');
        $model->setAttribute('sku', static::generateSku($model));
    });
Scott-David Jones
  • 292
  • 1
  • 6
  • 22
0

You can define a setter mutator in your model, so you can make there the MD5 hash and set it to a model property before it get saved.

docs: https://laravel.com/docs/5.7/eloquent-mutators

nyu.exe
  • 317
  • 1
  • 9
  • 1
    this doesnt work as it expects a value to be passed first then mutate that value, so if you dont call $model->sku = '' the mutator doesnt get called. – Scott-David Jones Jan 04 '19 at 12:04
  • You said: 'other field values' so, when all the model is set with its properties, you can have a last property, where you set something, that concats the rest of that model instance properties :) – nyu.exe Jan 04 '19 at 12:25