Installation:
composer require delatbabel/elocryptfive
Add to config/app.php under providers:
Delatbabel\EloquentEncrypt\ServiceProvider::class,
Publish Config:
php artisan vendor:publish --provider="Delatbabel\EloquentEncrypt\ServiceProvider"
Configure encryption key in .env:
ELOCRYPT_KEY=your-32-byte-base64-encoded-key
First Use Case: Define an encrypted attribute in your model:
use Delatbabel\EloquentEncrypt\Encryptable;
class User extends Model
{
use Encryptable;
protected $encryptable = ['credit_card', 'ssn'];
}
Now credit_card and ssn will auto-encrypt on save and decrypt on retrieval.
Attribute-Level Encryption:
$encryptable array:
protected $encryptable = ['api_key', 'password_hash'];
Dynamic Encryption:
encrypt()/decrypt() methods manually:
$user->encrypt('ssn', '123-45-6789'); // Force encrypt
$plaintext = $user->decrypt('ssn'); // Force decrypt
Querying Encrypted Fields:
whereEncrypted() for encrypted column queries:
User::whereEncrypted('ssn', '123-45-6789')->get();
Mass Assignment:
fill()/create():
User::create(['name' => 'John', 'ssn' => '123-45-6789']);
TEXT/LONGTEXT) for encrypted fields.doctrine/dbal for dynamic column type adjustments:
Schema::table('users', function (Blueprint $table) {
$table->text('ssn')->change(); // If upgrading from VARCHAR
});
protected $hidden = ['ssn', 'credit_card'];
Key Management:
config/cache.Column Size Limits:
VARCHAR(255) → TEXT upgrades.ssn may encrypt to 128+ chars.Query Performance:
whereEncrypted() requires plaintext comparison (decrypts internally). Avoid on large datasets.Serialization:
protected $dontEncryptInCache = ['ssn'];
Check Encryption Tags:
__ELOCRYPT__:. If missing, the field wasn’t encrypted.dd($user->getAttribute('ssn')); // Inspect raw value
Key Validation:
$encrypted = $user->ssn;
$decrypted = \Delatbabel\EloquentEncrypt\Encryptor::decrypt($encrypted);
Custom Encryptors:
Delatbabel\EloquentEncrypt\Contracts\Encryptor for alternative algorithms (e.g., AES-256):
class CustomEncryptor implements Encryptor {
public function encrypt($value) { ... }
public function decrypt($value) { ... }
}
ServiceProvider:
$this->app->bind('encryptor', function () {
return new CustomEncryptor();
});
Event Hooks:
eloquent.encrypting/eloquent.decrypting events to log or modify behavior:
Event::listen('eloquent.encrypting', function ($model, $attribute) {
if ($attribute === 'ssn') {
// Pre-process sensitive data
}
});
Conditional Encryption:
$encryptable based on user roles:
public function getEncryptable()
{
if (auth()->user()->isAdmin()) {
return ['api_key', 'ssn'];
}
return ['ssn'];
}
How can I help you explore Laravel packages today?