Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Db Encrypter Laravel Package

betterapp/laravel-db-encrypter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require betterapp/laravel-db-encrypter
    

    Publish the config file:

    php artisan vendor:publish --provider="BetterApp\LaravelDbEncrypter\LaravelDbEncrypterServiceProvider"
    
  2. Configure Encrypted Attributes: In your model, define $encryptable:

    protected $encryptable = ['credit_card_number', 'ssn'];
    
  3. 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
    
  4. Verify Encryption: Check the database—values in $encryptable will appear as ciphertext.


Implementation Patterns

Workflows

  1. Attribute-Level Encryption:

    • Use $encryptable for fields requiring encryption (e.g., PII, passwords).
    • Example:
      class Patient extends Model {
          protected $encryptable = ['medical_history', 'insurance_id'];
      }
      
  2. Dynamic Encryption:

    • Encrypt only when needed via encrypt()/decrypt() methods:
      $user->encrypt('credit_card_number');
      $user->decrypt('credit_card_number');
      
  3. Mass Assignment:

    • Encrypt during create()/update():
      User::create([
          'email' => 'user@example.com',
          'credit_card_number' => '4111111111111111' // Auto-encrypted
      ]);
      
  4. API Responses:

    • Use toArray() or toJson()—encrypted fields are decrypted automatically.

Integration Tips

  • Migrations: Update column types to TEXT for encrypted fields to avoid truncation.
  • Queries: Encrypted fields work seamlessly with Eloquent queries (e.g., where('ssn', 'like', '%123%')).
  • Caching: Encrypted data is cached per model instance; avoid redundant decryption in loops.
  • Testing: Mock Crypt::encrypt()/decrypt() in unit tests:
    $this->partialMock(Crypt::class, function ($mock) {
        $mock->shouldReceive('encrypt')->andReturn('encrypted_value');
    });
    

Gotchas and Tips

Pitfalls

  1. Column Size:

    • Encrypted values can grow ~33% (AES-256 + IV). Use TEXT or verify VARCHAR length.
    • Example migration:
      Schema::table('users', function (Blueprint $table) {
          $table->text('ssn')->change(); // Upgrade from VARCHAR
      });
      
  2. Case Sensitivity:

    • $encryptable is case-sensitive. Use exact field names (e.g., sn vs SN).
  3. Serialization:

    • Avoid encrypting fields used in serialize()/unserialize() (e.g., cache keys). Decryption fails on corrupted ciphertext.
  4. Database Backups:

    • Encrypted data is stored as ciphertext. Ensure backups include the database (not just decrypted dumps).
  5. Laravel 12+:

    • Uses Laravel’s built-in Crypt facade. If customizing encryption, extend BetterApp\LaravelDbEncrypter\Encrypter.

Debugging

  • Corrupted Data:

    • If decryption fails, check for:
      • Manual ciphertext edits in the database.
      • Incomplete writes (e.g., interrupted save()).
    • Fix: Re-encrypt the field or restore from backup.
  • Performance:

    • Heavy encryption/decryption in loops? Use static $encrypted = [] to cache decrypted values:
      public function getCreditCardNumberAttribute($value) {
          return $this->encrypted['credit_card_number'] ?? $value;
      }
      

Extension Points

  1. Custom Encryption:

    • Bind a custom encryptor via the config:
      'encryptor' => \App\Services\CustomEncrypter::class,
      
    • Implement BetterApp\LaravelDbEncrypter\Contracts\Encrypter.
  2. Partial Encryption:

    • Override encrypt()/decrypt() for conditional logic:
      public function encrypt($attribute) {
          if ($attribute === 'ssn' && $this->isAdmin()) {
              return parent::encrypt($attribute);
          }
          return $this->$attribute;
      }
      
  3. Query Scopes:

    • Encrypted fields work with scopes, but avoid decrypting in 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();
      
  4. Laravel Sanctum/Passport:

    • Encrypted fields are not included in API tokens by default. Exclude them from $hidden or $visible:
      protected $hidden = ['remember_token', 'encrypted_field'];
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware