magros/laravel-model-encryption
Installation:
composer require magros/laravel-model-encryption
Register Provider:
Add to config/app.php:
'providers' => [
\Magros\Encryptable\EncryptServiceProvider::class,
],
Publish Config:
php artisan vendor:publish --provider="Magros\Encryptable\EncryptServiceProvider"
This generates config/encrypt.php (default encryption key: APP_KEY).
First Use Case:
Apply the Encryptable trait to a model (e.g., User.php):
use Magros\Encryptable\Encryptable;
class User extends Model
{
use Encryptable;
protected $encryptable = ['ssn', 'credit_card']; // Fields to encrypt
}
Now, ssn and credit_card are auto-encrypted on save and decrypted on access.
Define Encryptable Fields:
Specify fields in $encryptable array (e.g., ['password', 'api_key']).
protected $encryptable = ['sensitive_data'];
Automatic Encryption/Decryption:
fill() or create().Querying Encrypted Fields:
Use whereEncrypted() for encrypted field queries:
User::whereEncrypted('ssn', '123-45-6789')->get();
Custom Encryption Logic:
Override getEncryptableAttribute() or setEncryptableAttribute() for field-specific logic:
public function getEncryptableAttribute($key)
{
if ($key === 'ssn') {
return str_replace('-', '', parent::getEncryptableAttribute($key));
}
return parent::getEncryptableAttribute($key);
}
toArray() or toJson()—encrypted fields are decrypted automatically.required|string).remember()) if sensitive data is involved.Double Encryption:
Encryptable and Appends/Attributes, ensure no conflicts:
// Bad: May encrypt twice
protected $appends = ['encrypted_field'];
protected $encryptable = ['encrypted_field'];
$encryptable.Query Performance:
whereEncrypted() requires decryption for comparison. For large datasets, consider:
// Pre-encrypt the value and use raw SQL
DB::table('users')->where('ssn', encrypt('123-45-6789'))->get();
Serialization Issues:
serialize()/unserialize(). Use toArray() for storage:
cache()->put('user', $user->toArray());
Key Management:
APP_KEY. For production, use environment variables:
// config/encrypt.php
'key' => env('ENCRYPTION_KEY'),
\Log::debug('DB Value:', $user->getRawOriginal('ssn'));
\Log::debug('Model Value:', $user->ssn);
$encryptable = [] in tests to bypass encryption.EncryptServiceProvider:
$this->app->bind('encrypt', function () {
return new CustomEncryptionDriver();
});
getEncryptableAttribute() to implement per-field logic (e.g., hashing + encryption).update()/delete(), ensure encrypted fields are handled:
User::where('id', 1)->update(['ssn' => '123-45-6789']); // Works
How can I help you explore Laravel packages today?