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

Svennnn's avatar

How does the encrypted object-casting work?

Hey,

The docs at https://laravel.com/docs/12.x/eloquent-mutators#encrypted-casting mention encrypted:object to cast a col autoencrypted to an object. That sounds great, but I can not find examples of how to do it.

Do I still need my own custom Casting-Class or should the ValueObject be enought?

I tried it like this

class Profile extends Model
{
    protected $casts = [
        'verified_information' => 'encrypted:object,App\ValueObjects\VerifiedInformation',
    ];
}

class VerifiedInformation
{
    public function __construct(
        public string $prename,
        public string $surname,
        public int $salary
    ) {}

    public function __toString()
    {
        return json_encode([
            'prename' => $this->prename,
            'surname' => $this->surname,
            'salary' => $this->salary
        ]);
    }
}

But that has multiple issues:

  1. The object is still stored in plain text
  2. Fetched values are not casted back into the object

I hoped that the ':object'-part would somehow do lifting for the dev.

1 like
7 replies
vincent15000's avatar

Have you tried with a simple string ?

class Profile extends Model
{
    protected $casts = [
        'test' => 'encrypted',
    ];
}

Just to check if it works for a simple string.

vincent15000's avatar

@Svennnn Furthermore, I'm not sure that you really have to return a JSON encoded value if you need to handle an object. Laravel can do this automatically with an object casting and it's visibly also possible with an encrypted object casting. But this has to be confirmed, because I never worked with encrypted objects.

vincent15000's avatar
Level 63

@Svennnn

Why not just encrypted:object instead of encrypted:object,App\ValueObjects\VerifiedInformation ?

I don't see anything in the documentation saying that it's necessary to specify the object model.

1 like
Svennnn's avatar

@vincent15000 Oh! That actually does the trick! The downside is that after fetching the stuff becomes a stdClass instead of an instance of my own class, but maybe then I need a custom cast for that and I overestimated what the internal casting can do

1 like
vincent15000's avatar

@Svennnn You can effectively also try to create your own casting class, but I can't really help you this way, because I never created my own casting class.

Please or to participate in this conversation.