betterapp/laravel-db-encrypter
Installation:
composer require betterapp/laravel-db-encrypter
Publish the config file:
php artisan vendor:publish --provider="BetterApp\LaravelDbEncrypter\LaravelDbEncrypterServiceProvider"
Configure Encrypted Attributes:
In your model, define $encryptable:
protected $encryptable = ['credit_card_number', 'ssn'];
First Use Case:
$user = new User();
$user->credit_card_number = '4111111111111111'; // Automatically encrypted on save
$user->save();
// Decrypted automatically on retrieval
echo $user->credit_card_number; // Plaintext
Verify Encryption:
Check the database—values in $encryptable will appear as ciphertext.
Attribute-Level Encryption:
$encryptable for fields requiring encryption (e.g., PII, passwords).class Patient extends Model {
protected $encryptable = ['medical_history', 'insurance_id'];
}
Dynamic Encryption:
encrypt()/decrypt() methods:
$user->encrypt('credit_card_number');
$user->decrypt('credit_card_number');
Mass Assignment:
create()/update():
User::create([
'email' => 'user@example.com',
'credit_card_number' => '4111111111111111' // Auto-encrypted
]);
API Responses:
toArray() or toJson()—encrypted fields are decrypted automatically.TEXT for encrypted fields to avoid truncation.where('ssn', 'like', '%123%')).Crypt::encrypt()/decrypt() in unit tests:
$this->partialMock(Crypt::class, function ($mock) {
$mock->shouldReceive('encrypt')->andReturn('encrypted_value');
});
Column Size:
TEXT or verify VARCHAR length.Schema::table('users', function (Blueprint $table) {
$table->text('ssn')->change(); // Upgrade from VARCHAR
});
Case Sensitivity:
$encryptable is case-sensitive. Use exact field names (e.g., sn vs SN).Serialization:
serialize()/unserialize() (e.g., cache keys). Decryption fails on corrupted ciphertext.Database Backups:
Laravel 12+:
Crypt facade. If customizing encryption, extend BetterApp\LaravelDbEncrypter\Encrypter.Corrupted Data:
save()).Performance:
static $encrypted = [] to cache decrypted values:
public function getCreditCardNumberAttribute($value) {
return $this->encrypted['credit_card_number'] ?? $value;
}
Custom Encryption:
'encryptor' => \App\Services\CustomEncrypter::class,
BetterApp\LaravelDbEncrypter\Contracts\Encrypter.Partial Encryption:
encrypt()/decrypt() for conditional logic:
public function encrypt($attribute) {
if ($attribute === 'ssn' && $this->isAdmin()) {
return parent::encrypt($attribute);
}
return $this->$attribute;
}
Query Scopes:
where() clauses:
// ❌ Avoid (decrypts all records)
User::where('ssn', 'like', '%123%')->get();
// ✅ Better (use raw queries or custom logic)
User::whereRaw("ssn LIKE ?", ['%123%'])->get();
Laravel Sanctum/Passport:
$hidden or $visible:
protected $hidden = ['remember_token', 'encrypted_field'];
How can I help you explore Laravel packages today?