Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andreazorzi's avatar

Laravel 10 - model cast encrypted 'The payload is invalid.'

Hi, I have this issue with model encryption cast. The problem seems to appear only when I use the create method of a model with protected cast set to encrypted for certain columns. When I try to create a new entry, it gives me the error 'The payload is invalid.', but when I check in the database the data was actually added and the values are crypted. If I look where the exception happens, I get this message:

exception: "Illuminate\\Contracts\\Encryption\\DecryptException"

It seems that the error occurs after the data were stored in the database, then Laravel tries to return the model object decrypting the values, failing (I think Laravel tries to decrypt plain data). But if I try to get this model data and display them in a page, I have no error and the encrypted data was actually decrypted. Anyone has the same issue?

Below I put my code

Migration

Schema::create('Strutture', function (Blueprint $table) {
    $table->string('Struttura');
    $table->string('Nome');
    $table->text('Username')->nullable();
    $table->text('Password')->nullable();
    $table->text('Wskey')->nullable();

    $table->primary('Struttura');
});

Strutture class

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Struttura extends Model
{
    protected $table = 'Strutture';
    protected $primaryKey = 'Struttura';
    public $incrementing = false;
    public $timestamps = false;
    
    protected $fillable = ['Struttura', 'Nome', 'Username', 'Password', 'Wskey'];
    protected $attributes  = [
        'Nome' => '',
        'Username' => '',
        'Password' => '',
        'Wskey' => ''
    ];
    
    public static function createFromJson(string $json){
        $json = json_decode($json, true);
        
        if(is_null($json)){
            return [
                "status" => false,
                "error" => "Invalid JSON"
            ];
        }
        
        foreach($json as $key => $data){
            if(!$test_login["status"]){
                $errors[] = $key;
                continue;
            }
            
            Struttura::updateOrCreate([
                'Struttura' => $key
            ],
            [
                'Nome' => $data['name'],
                'Username' => $data['username'],
                'Password' => $data['password'],
                'Wskey' => $data['wskey']
            ]);
        }
        
        return [
            "status" => true
        ];
    }
    
    protected $casts = [
        'Username' => "encrypted",
        'Password' => "encrypted",
        'Wskey' => "encrypted"
    ];
}
0 likes
0 replies

Please or to participate in this conversation.