Installation:
composer require al-saloul/encryption
Publish the config file (if needed):
php artisan vendor:publish --provider="AlSaloul\Encryption\EncryptionServiceProvider"
Basic Usage: Encrypt a number:
use AlSaloul\Encryption\Facades\Encryption;
$encrypted = Encryption::encrypt(12345);
// Output: e.g., "x9#kL2$pQ7"
Decrypt a string:
$decrypted = Encryption::decrypt($encrypted);
// Output: 12345
First Use Case: Securely store sensitive numeric data (e.g., credit card last 4 digits, user IDs) in logs, URLs, or databases without exposing raw values.
Data Storage:
$user->secure_id = Encryption::encrypt($user->id);
$user->save();
$id = Encryption::decrypt($user->secure_id);
API Responses:
return response()->json([
'user_id' => Encryption::encrypt($user->id),
'last_four' => Encryption::encrypt($payment->last_four),
]);
URL Parameters:
$encryptedId = Encryption::encrypt($order->id);
route('order.show', ['id' => $encryptedId]);
$order = Order::find(Encryption::decrypt(request('id')));
Validation:
if (Encryption::isEncrypted($input)) {
$decrypted = Encryption::decrypt($input);
// Proceed with $decrypted
}
Middleware: Create middleware to auto-decrypt encrypted IDs in routes:
public function handle($request, Closure $next) {
$request->merge([
'id' => Encryption::decrypt($request->id)
]);
return $next($request);
}
Eloquent Accessors/Mutators:
public function getSecureIdAttribute($value) {
return Encryption::encrypt($this->attributes['id']);
}
public function setSecureIdAttribute($value) {
$this->attributes['id'] = Encryption::decrypt($value);
}
Logging: Use the logging feature to track encryption/decryption:
Encryption::enableLogging();
Encryption::encrypt(123); // Logs the operation
Input Validation:
if (!Encryption::isEncrypted($string)) {
throw new \InvalidArgumentException("Invalid encrypted string");
}
Config Overrides:
config/encryption.php may break decryption if not symmetric:
'mappings' => [
'0' => 'a', '1' => 'b', // Custom mappings
],
'padding' => [
'prefix_length' => 3,
'suffix_length' => 3,
],
Edge Cases:
PHP_INT_MAX).Security:
encrypt()) for such cases.random_int() internally).Failed Decryption:
mappings and padding.Logging: Enable logging to trace operations:
Encryption::enableLogging();
// Check Laravel logs for entries like:
// "[Encryption] Encrypted '123' to 'x9#kL2$pQ7'"
Custom Mappings: Override mappings in the config or dynamically:
Encryption::setMappings(['0' => 'X', '1' => 'Y']);
Custom Padding:
Extend the Encryption facade to add dynamic padding:
Encryption::setPadding(5, 5); // 5-char prefix/suffix
Event Listeners: Listen for encryption/decryption events (if the package supports them):
Encryption::onEncrypted(function ($original, $encrypted) {
// Custom logic
});
Testing: Mock the facade for unit tests:
$this->partialMock(Encryption::class, function ($mock) {
$mock->shouldReceive('decrypt')->andReturn(123);
});
How can I help you explore Laravel packages today?