Hi all, I've been away from programming for a long time expect a couple years ago when I started playing with Laravel to move an 18 year old php3 site to a more modern server and updated look. After all these years I am excited to be getting back to programming again as I've left paid employment (non-program related) and have committed to donating my time to develop software for a non-profit organization. I'm really loving Laravel 5.3 and it is sure exciting to see how far php has come.
Okay, on to my issue. I am making use of a Trait that is attached to all my models with the purpose being to encrypt and unencrypt data stored in the database and it worked well until I tried applying a mutator on one of those columns/attributes.
The issue I've run into is if I do a mutator on an attribute such as formatting a phone number, the encryption is done before that mutator is called so it's mutating the encrypted code which is of course not going to work.
In the trait my code to encrypt the attribute currently is:
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
The mutator in the model is as:
public function setNumberAttribute($value)
{
$this->attributes['number'] = preg_replace("/[^[:digit:]]/u", '', $value);
}
So the trait's setAttribute() is being called first so it encrypts the $value, then the model's mutator setNumberAttribute($value) is being set.
I've tried various things to get the "set" mutator running before the trait but the deeper I dig the more that looks like I'm opening a can of worms. So at this point I see two directions I can go.
One is to move the encryption into mutators for each column to be encrypted in the database. That's a lot of repetition so not ideal but it would work.
The other direction is to replace my EncryptionTrait with a bigger MutatorTrait where I check for parameters set in the model of what attributes need what mutators and in what order and then it can call them dynamically. I think the only downside to that is then this can get to be a big Trait is being attached to every model.
I know Laravel sometimes has these hidden gems that just are not well known plus lots of you grasp PHP 5 and 7 OOP more than I do (I pretty much got out of programming just as php 5 was coming out) so I'm wondering if others have perhaps a simpler or better solution that I'm just not seeing (outside of the two options I've suggested of course).