How to deal with encrypted data when editing

What seems to be the problem:
I have certain database fields that need to be encrypted due to law and currently, I am using a Trait called Encryptable where the encryption and decryption are done.
When editing it is pulling the encrypted data and it is not decrypting it.

I am using livewire version 2

Trait:
<?PHP

namespace App\Traits;

use Illuminate\Support\Facades\Crypt;

trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decryptString($value);
        }

        return $value;
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encryptString($value);
        }

        return parent::setAttribute($key, $value);
    }
}

Model

protected $encryptable = [
'identity_number',
];

Livewire Component

public function rules()
{
    return [
        'user.identity_number' => 'required',
    ];
}

Blade File

<x-form.group>
    <x-form.input.group label="{!! trans('global.form.label.identity_number') !!}" 
       for="user.identity_number">
             <x-form.input.text
                    wire:model.lazy="user.identity_number"
                    type="text"
                    id="user.identity_number"
                    name="user.identity_number"
                    :value="old('user.identity_number')"
                    class="{{ ($errors->first('user.identity_number')) ? 'is-invalid' : ''}}" />
              <x-form.input.validation-error for="user.identity_number" />
           </x-form.input.group>
     </x-form.group>

This is what is shown when editing

image

Hey, @migs87

Take a look at this thread:

Thanks, @skywalker, I really appreciate the response.

I did have a look at that thread and I did try it out but I did not come right. The Trait I created might be conflicting.

I did however manage to resolve the issue by adding the following to the mount method.

Liverwire Component

public function mount(User $user)
{
    $this->identityNumber = $user->identity_number;
}

Added:

public $identityNumber = null;

And then changed the following:

Liverwire Component

public function rules()
{
    return [
        'identityNumber' => 'required',
    ];
}

Blade File

<x-form.group>
    <x-form.input.group label="{!! trans('global.form.label.identity_number') !!}" for="identityNumber">
         <x-form.input.text
             wire:model.lazy="identityNumber"
             type="text"
             id="identityNumber"
            name="identityNumber"
            :value="old('identityNumber')"
            class="{{ ($errors->first('identityNumber')) ? 'is-invalid' : ''}}" />
      <x-form.input.validation-error for="identityNumber" />
  </x-form.input.group> 
</x-form.group>

That’s Greet! Good to know you solved your problem :smiley:

Happy coding mate.

1 Like