PHP code example of vimatech / laravel-secure-fields

1. Go to this page and download the library: Download vimatech/laravel-secure-fields 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/ */

    

vimatech / laravel-secure-fields example snippets


use VimaTech\SecureFields\Casts\SecureField;
use VimaTech\SecureFields\Casts\SecureJson;
use VimaTech\SecureFields\Traits\HasSecureFields;

class User extends Model
{
    use HasSecureFields;

    protected $casts = [
        'email'    => SecureField::class,
        'phone'    => SecureField::class,
        'ssn'      => SecureField::class,
        'metadata' => SecureJson::class,
    ];

    protected array $secureSearchable = [
        'email',
        'phone',
    ];
}

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->text('email');                       //     // optional field
    $table->string('phone_hash', 64)->nullable();
    $table->text('ssn');
    $table->text('metadata')->nullable();        // optional JSON field
    $table->timestamps();
});

// Create — automatically encrypted
$user = User::create([
    'email' => '[email protected]',
    'phone' => '+1234567890',
    'ssn'   => '123-45-6789',
    'metadata' => ['plan' => 'premium', 'preferences' => ['dark_mode' => true]],
]);

// Read — automatically decrypted
echo $user->email; // "[email protected]"

// The database stores encrypted ciphertext — never plaintext

// Exact-match search on encrypted field
$user = User::secureWhere('email', '[email protected]')->first();

// Chain with other queries
$users = User::secureWhere('phone', '+1234567890')
    ->where('active', true)
    ->get();

User::secureWhere('email', '[email protected]')
User::secureWhere('email', '  [email protected]  ')
User::secureWhere('email', '[email protected]')

$user->masked('phone');       // "********7890"
$user->masked('ssn');         // "*******6789"
$user->masked('phone', 2);    // "**********90"

// Returns all model fields with secure fields replaced by masked values
$user->toMaskedArray();       // ['id' => 1, 'phone' => '********7890', ...]

$user->masked('phone', visibleEnd: 4, maskChar: '#'); // "########7890"

protected $casts = [
    'metadata' => SecureJson::class,
];

// Works like a normal JSON cast, but encrypted at rest
$user->metadata = ['api_key' => 'sk_live_...', 'tokens' => 42];
$user->save();

echo $user->metadata['api_key']; // "sk_live_..."

$user->toArray();        // email, phone, ssn are excluded
$user->toSecureArray();  // same — always excludes all encrypted fields
$user->toMaskedArray();  // 

use VimaTech\SecureFields\Facades\SecureFields;

// Encrypt/decrypt manually
$encrypted = SecureFields::encrypt('sensitive data');
$decrypted = SecureFields::decrypt($encrypted);

// Hash for searching
$hash = SecureFields::hash('[email protected]');
$matches = SecureFields::verifyHash('[email protected]', $hash); // true

// config/secure-fields.php

return [
    // Base64-encoded 32-byte encryption key.
    // REQUIRED in production — see "Generating Keys" section.
    // Falls back to HKDF derivation from APP_KEY if not set (not recommended).
    'key' => env('SECURE_FIELDS_KEY'),

    'cipher' => 'aes-256-gcm',

    'hashing' => [
        // Minimum 32 bytes. REQUIRED in production.
        // Falls back to HKDF derivation from APP_KEY if not set (not recommended).
        'key'       => env('SECURE_FIELDS_HASH_KEY'),
        'algorithm' => 'sha256',
    ],

    'rotation' => [
        'chunk_size' => 500,
        'queue'      => env('SECURE_FIELDS_QUEUE'),
        'connection' => env('SECURE_FIELDS_QUEUE_CONNECTION'),
    ],

    'masking' => [
        'character'   => '*',
        'visible_end' => 4,
    ],

    'audit' => [
        'enabled'     => env('SECURE_FIELDS_AUDIT', false),
        'driver'      => env('SECURE_FIELDS_AUDIT_DRIVER', 'log'), // 'database' or 'log'
        'log_channel' => env('SECURE_FIELDS_AUDIT_CHANNEL', 'stack'),
    ],
];

use VimaTech\SecureFields\Casts\SecureField;
use VimaTech\SecureFields\Casts\SecureJson;
use VimaTech\SecureFields\Traits\HasSecureFields;

// 1. Define your model
class User extends Model
{
    use HasSecureFields;

    protected $casts = [
        'email'    => SecureField::class,
        'phone'    => SecureField::class,
        'ssn'      => SecureField::class,
        'metadata' => SecureJson::class,
    ];

    protected array $secureSearchable = ['email', 'phone'];
}

// 2. Use it naturally
$user = User::create([
    'email'    => '[email protected]',
    'phone'    => '+1234567890',
    'ssn'      => '123-45-6789',
    'metadata' => ['plan' => 'premium'],
]);

$user->email;           // "[email protected]" (decrypted)
$user->masked('phone'); // "********7890"
$user->masked('ssn');   // "*******6789"

// 3. Search encrypted fields
User::secureWhere('email', '[email protected]')->first();
User::secureWhere('email', '[email protected]')->first(); // same result — case-insensitive

// 4. Serialization is safe by default
$user->toArray();       // email, phone, ssn excluded
$user->toMaskedArray(); // ['id' => 1, 'email' => '**************com', ...]
bash
php artisan vendor:publish --tag=secure-fields-config
bash
php artisan vendor:publish --tag=secure-fields-migrations
php artisan migrate
bash
php -r "echo base64_encode(random_bytes(32)), PHP_EOL;"
bash
php -r "echo bin2hex(random_bytes(32)), PHP_EOL;"
bash
> OLD_KEY=$(vault kv get -field=old_key secret/secure-fields)
> php artisan secure-fields:rotate "App\Models\User" --old-key="$OLD_KEY"
> 
bash
php artisan vendor:publish --tag=secure-fields-migrations
php artisan migrate
bash
composer analyse