Installation
composer require crudly/encrypted
Add the service provider to config/app.php:
'providers' => [
// ...
Crudly\Encrypted\EncryptedServiceProvider::class,
],
Basic Usage Define an encrypted attribute in your Eloquent model:
use Crudly\Encrypted\Encrypted;
class User extends Model
{
protected $casts = [
'credit_card' => Encrypted::class,
];
}
First Use Case
// Encrypt on set
$user = new User();
$user->credit_card = '4111111111111111'; // Automatically encrypted
// Decrypt on get
$card = $user->credit_card; // Returns decrypted value
config/encrypted.php (default encryption settings)app/Models/User.php (model-level configuration)database/migrations/ (ensure encrypted fields are stored as text or longtext)Selective Encryption
// Encrypt only specific fields
protected $casts = [
'ssn' => Encrypted::class,
'medical_history' => Encrypted::class,
];
Custom Encryption Keys
Override the default key in config/encrypted.php:
'key' => env('ENCRYPTION_KEY', 'default-key-32-characters-long'),
Querying Encrypted Fields
Use whereRaw for encrypted comparisons:
User::whereRaw('encrypted(credit_card) = ?', ['4111111111111111'])->get();
Mass Assignment
$user = User::create([
'name' => 'John Doe',
'credit_card' => '4242424242424242', // Encrypted automatically
]);
$user->only(['id', 'name']) to exclude encrypted fields from JSON responses.$this->app->instance(Encrypted::class, MockEncrypted::class);
Field Type Mismatch
text or longtext in MySQL (or equivalent in other DBs). Using varchar will corrupt data.Key Management
ENCRYPTION_KEY=your-32-byte-key-here
Query Limitations
where(), orderBy(), or groupBy(). Use whereRaw instead.Serialization Issues
session()->put('user', $user)). Use ->toArray() first.config/encrypted.php for correct key length (must be 32 bytes for AES-256).APP_DEBUG=true) to catch encryption errors.DB::enableQueryLog() to verify raw SQL queries when debugging whereRaw.Custom Encryption Algorithm
Bind a custom encryptor in AppServiceProvider:
$this->app->bind(Encrypted::class, function () {
return new CustomEncrypted();
});
Attribute-Level Configuration
Pass options to Encrypted:
protected $casts = [
'api_key' => [Encrypted::class, 'algorithm' => 'AES-128'],
];
Global Exclusions
Exclude models from encryption entirely in EncryptedServiceProvider:
protected $except = [
'App\Models\AuditLog',
];
How can I help you explore Laravel packages today?