0

I am trying to store a key into my database and I want it to be encrypted and decrypted.

So I use Laravel 9 mutator: https://laravel.com/docs/9.x/eloquent-mutators

protected function privateKey(): Attribute
{
    return Attribute::make(
        get: fn ($value) => Crypt::decryptString($value),
        set: fn ($value) => Crypt::encryptString($value),
    );
}

and I accessed it to one of my service class:

$provider = Provider::findOrFail($id);
$privateKey = $provider->private_key;

However, phpstan throws error saying:

Access to an undefined property App\Models\Method|Illuminate\Database\Eloquent\Collection<int,                                
         App\Models\Provider>::$private_key

However, when I tried using the old way of mutating and accessing attributes, it worked:

public function setPrivateKeyAttribute(string $value): void
{
    if (!empty($value)) {
        $this->attributes['private_key'] = Crypt::encryptString($value);
    }
}

public function getPrivateKeyAttribute(string $value): string
{
    return Crypt::decryptString($value);
}

and at this point, I don't have any idea why. is this a bug in the side of phpstan? if not, how can I resolve the issue?

nwantiti
  • 41
  • 4

1 Answers1

0

The answer from Kobayakawa in this post from Laracast helped me to answer this.

You should define the return type and what it allowed to be inserted in the mutator. For your example it should be something like this:

/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute<Provider, string>
 */
protected function privateKey(): Attribute
{
    return Attribute::make(
        get: fn ($value) => Crypt::decryptString($value),
        set: fn ($value) => Crypt::encryptString($value),
    );
}

In my own example I don't define a 'getter'. But you should still define it, because it will still be returned.

/**
 * @return \Illuminate\Database\Eloquent\Casts\Attribute<Webhook, array>
 */
protected function webhook(): Attribute
{
    return Attribute::make(
        set: fn (array $value) => self::createWebhook($value),
    );
}
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Remy
  • 25
  • 4