Home > Software design >  Error when updating an encrypted value in a database table (The payload is invalid)
Error when updating an encrypted value in a database table (The payload is invalid)

Time:02-04

My passport field is as a string in my judokas migration. I want to encrypt this field and leave it only decrypted in the view and in the update form field, when creating the record everything is fine, the field is encrypted. The problem is when I do a test by changing the value of the passport the error The payload is invalid at the line return Crypt::decryptString($value);

<?php

namespace App\Models;

use App\Events\FighterDeletedEvent;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;

class JudokaModel extends Model
{
    use HasFactory;
    public $timestamps = false;
    protected $table = 'jodokas';
    protected $primaryKey = 'id';
    protected $fillable = [
        'passaport',
    ];

    public function setPassaportAttribute($value)
    {
        $this->attributes['passaport'] = Crypt::encryptString($value);
    }

    public function getPassaportAttribute($value)
    {
        return Crypt::decryptString($value); // The payload is invalid.
    }
}

How do fix this problem?

CodePudding user response:

Try catching the DecryptException and return a default value if the decryption fails.

public function getPassaportAttribute($value)
{
    try {
        return Crypt::decryptString($value);
    } catch (DecryptException $e) {
        return $value;
    }
}
  • Related