PHP code example of richardstyles / eloquentencryption

1. Go to this page and download the library: Download richardstyles/eloquentencryption library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

richardstyles / eloquentencryption example snippets


Schema::create('sales_notes', function (Blueprint $table) {
    $table->increments('id');
    $table->encrypted('private_data');
    $table->encrypted('optional_private_data')->nullable();
    $table->timestamps();
});



namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Model;
use RichardStyles\EloquentEncryption\EloquentEncryption;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Configure all models to use RSA encryption for encrypted casts
        Model::encryptUsing(new EloquentEncryption());
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'ssn' => 'encrypted',                      // String
        'preferences' => 'encrypted:array',        // Array
        'metadata' => 'encrypted:json',            // JSON
        'settings' => 'encrypted:object',          // Object
        'tags' => 'encrypted:collection',          // Collection
    ];
}

// Create a user with encrypted data
$user = User::create([
    'name' => 'John Doe',
    'ssn' => '123-45-6789',              // Automatically encrypted when saved
    'preferences' => ['theme' => 'dark'], // Automatically encrypted as JSON
]);

// Access decrypted data (automatic)
echo $user->ssn;                 // '123-45-6789' (decrypted automatically)
echo $user->preferences['theme']; // 'dark' (decrypted automatically)

// Update encrypted data
$user->ssn = '987-65-4321';      // Will be encrypted when saved
$user->save();

// Raw database value (binary encrypted data)
DB::table('users')->value('ssn'); // Returns encrypted binary data

// Through the model (automatic decryption)
User::find(1)->ssn; // Returns decrypted '123-45-6789'

// config/eloquent_encryption.php
'key' => [
    'max_previous_keys' => 5, // Keep up to 5 previous key pairs
],

// This will decrypt with old key and re-encrypt with new key
User::chunk(100, function ($users) {
    foreach ($users as $user) {
        if ($user->highly_sensitive_field) {
            $user->save(); // Re-encrypts with new key
        }
    }
});



namespace App\Encryption;

use RichardStyles\EloquentEncryption\Contracts\RsaKeyHandler;

class VaultKeyHandler implements RsaKeyHandler
{
    public function exists(): bool
    {
        // Check if keys exist in your vault
    }

    public function getPublicKey(): string
    {
        // Retrieve public key from vault
    }

    public function getPrivateKey(): string
    {
        // Retrieve private key from vault
    }

    public function getPreviousKeys(): array
    {
        // Return array of previous key pairs with metadata:
        // [
        //   ['publickey' => '...', 'privatekey' => '...', 'rotated_at' => '...'],
        //   ...
        // ]
    }

    public function rotateKeys(string $newPublic, string $newPrivate): void
    {
        // Move current keys to previous, save new keys
    }

    // Implement remaining interface methods...
}

// config/eloquent_encryption.php
return [
    'handler' => \App\Encryption\VaultKeyHandler::class,
    // ... other config
];

  [
    [
      'publickey' => 'public key content',
      'privatekey' => 'private key content',
      'rotated_at' => '2026-02-22T14:45:00+00:00', // ISO 8601 timestamp
    ],
    // ... more previous keys
  ]
  
bash
php artisan vendor:publish --provider="RichardStyles\EloquentEncryption\EloquentEncryptionServiceProvider" --tag="config"
bash
php artisan encrypt:generate
bash
php artisan encrypt:rotate
 bash
vendor/bin/pest tests/Unit/EloquentEncryptionTest.php