PHP
Customizing Eloquent Attribute Casting for Complex Data Types in Laravel
Implement custom attribute casting in Laravel Eloquent to automatically serialize and deserialize complex data types like custom value objects or encrypted strings.
// 1. Define a Custom Cast class (e.g., app/Casts/EncryptedString.php)
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Crypt;
class EncryptedString implements CastsAttributes
{
public function get($model, $key, $value, array $attributes)
{
return $value ? Crypt::decryptString($value) : null;
}
public function set($model, $key, $value, array $attributes)
{
return $value ? Crypt::encryptString($value) : null;
}
}
// 2. Apply the custom cast to your model (e.g., app/Models/Setting.php)
namespace App\Models;
use App\Casts\EncryptedString;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $casts = [
'value' => EncryptedString::class,
];
protected $fillable = ['key', 'value'];
}
// 3. Usage Example
// Storing an encrypted setting
$setting = Setting::create(['key' => 'api_token', 'value' => 'my-secret-api-token-123']);
echo "Stored value (encrypted in DB): " . $setting->getAttributes()['value'] . "
";
// Retrieving the setting (automatically decrypted)
$retrievedSetting = Setting::where('key', 'api_token')->first();
echo "Retrieved value (decrypted): " . $retrievedSetting->value . "
";
How it works: Eloquent attribute casting provides a convenient way to convert model attributes to different data types. This snippet shows how to create a custom cast for encrypting and decrypting string attributes. The `EncryptedString` class implements `CastsAttributes`, with `get` for decryption when retrieving and `set` for encryption when storing. By assigning this cast in the `casts` array of the `Setting` model, the `value` attribute will be automatically encrypted before saving to the database and decrypted upon retrieval.