You cannot directly specify custom helper functions like 'username' => 'encrypt_data()' inside Laravel's $casts array. Laravel's $casts property only accepts native types (such as 'encrypted') or classes that implement the CastsAttributes interface.
However, you can achieve exactly what you want using either of the following two clean methods:
Method 1: Using a Custom Cast Class (Recommended & Reusable)
You can create a custom Cast class to wrap your helper functions:
Create the Cast class at app/Casts/CustomEncrypt.php:
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class CustomEncrypt implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
return decrypt_data($value);
}
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
return encrypt_data($value);
}
}
Use it in your casts inside Credential.php:
use App\Casts\CustomEncrypt;
protected $casts = [
'username' => CustomEncrypt::class,
'password' => CustomEncrypt::class,
'link' => CustomEncrypt::class,
];
Method 2: Using Eloquent Accessors & Mutators (No extra files)
use Illuminate\Database\Eloquent\Casts\Attribute;
protected function username(): Attribute
{
return Attribute::make(
get: fn ($value) => decrypt_data($value),
set: fn ($value) => encrypt_data($value),
);
}
protected function password(): Attribute
{
return Attribute::make(
get: fn ($value) => decrypt_data($value),
set: fn ($value) => encrypt_data($value),
);
}
protected function link(): Attribute
{
return Attribute::make(
get: fn ($value) => decrypt_data($value),
set: fn ($value) => encrypt_data($value),
);
}
Top comments (0)