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 Model Encryption Laravel Package

magros/laravel-model-encryption

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require magros/laravel-model-encryption
    
  2. Register Provider: Add to config/app.php:

    'providers' => [
        \Magros\Encryptable\EncryptServiceProvider::class,
    ],
    
  3. Publish Config:

    php artisan vendor:publish --provider="Magros\Encryptable\EncryptServiceProvider"
    

    This generates config/encrypt.php (default encryption key: APP_KEY).

  4. 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.


Implementation Patterns

Core Workflow

  1. Define Encryptable Fields: Specify fields in $encryptable array (e.g., ['password', 'api_key']).

    protected $encryptable = ['sensitive_data'];
    
  2. Automatic Encryption/Decryption:

    • Setters: Values are encrypted before saving to DB.
    • Getters: Values are decrypted when accessed.
    • Mass Assignment: Works seamlessly with fill() or create().
  3. Querying Encrypted Fields: Use whereEncrypted() for encrypted field queries:

    User::whereEncrypted('ssn', '123-45-6789')->get();
    
  4. 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);
    }
    

Integration Tips

  • API Responses: Use toArray() or toJson()—encrypted fields are decrypted automatically.
  • Validation: Validate encrypted fields as usual (e.g., required|string).
  • Relationships: Encryptable trait works with belongsTo/manyTo relationships. Ensure related models don’t double-encrypt.
  • Caching: Avoid caching decrypted values (e.g., remember()) if sensitive data is involved.

Gotchas and Tips

Pitfalls

  1. Double Encryption:

    • If a model uses Encryptable and Appends/Attributes, ensure no conflicts:
      // Bad: May encrypt twice
      protected $appends = ['encrypted_field'];
      protected $encryptable = ['encrypted_field'];
      
    • Fix: Exclude appended fields from $encryptable.
  2. 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();
      
  3. Serialization Issues:

    • Encrypted models may fail with serialize()/unserialize(). Use toArray() for storage:
      cache()->put('user', $user->toArray());
      
  4. Key Management:

    • Defaults to APP_KEY. For production, use environment variables:
      // config/encrypt.php
      'key' => env('ENCRYPTION_KEY'),
      

Debugging

  • Check Encryption: Log raw DB values vs. model values:
    \Log::debug('DB Value:', $user->getRawOriginal('ssn'));
    \Log::debug('Model Value:', $user->ssn);
    
  • Disable Encryption Temporarily: Set $encryptable = [] in tests to bypass encryption.

Extension Points

  1. Custom Encryption Driver: Bind a custom driver in EncryptServiceProvider:
    $this->app->bind('encrypt', function () {
        return new CustomEncryptionDriver();
    });
    
  2. Field-Specific Encryption: Use getEncryptableAttribute() to implement per-field logic (e.g., hashing + encryption).
  3. Bulk Operations: For update()/delete(), ensure encrypted fields are handled:
    User::where('id', 1)->update(['ssn' => '123-45-6789']); // Works
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope