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?

1 Answer 1

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),
    );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.