rpsimao / laravel-model-encryption
一个用于 Laravel 中加密数据模型的特质,自动加密和解密模型数据,通过覆盖 Eloquent 模型的 getAttribute 和 setAttribute 方法。
Requires
- php: >=7.1
- ext-openssl: *
- illuminate/database: ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
Requires (Dev)
- mockery/mockery: dev-master@dev
- orchestra/testbench: ~3.7
This package is not auto-updated.
Last update: 2024-09-19 16:43:53 UTC
README
laravel-model-encryption
一个用于 Laravel 中加密数据模型的特质,这个特质会自动加密和解密模型数据,通过覆盖 Eloquent 模型的 getAttribute 和 setAttribute 方法。
如何安装
运行 composer 安装
composer install magros/laravel-model-encryption
将 ServiceProvider 添加到你的 app/config.php 文件中
'providers' => [ ... \Magros\Encryptable\EncryptServiceProvider::class, ],
发布配置文件,这将创建 config/encrypt.php
php artisan vendor:publish --provider=Magros\Encryptable\EncryptServiceProvider
如何使用
-
你必须在 .env 文件中添加
ENCRYPT_KEY
和ENCRYPT_PREFIX
,或者在 config/encrypt.php 文件中设置它们 -
使用
Magros\Encryptable\Encryptable
特质use Magros\Encryptable\Encryptable;
-
在你的模型上设置
$encryptable
数组。protected $encryptable = ['encrypted_property'];
-
这里有一个完整的示例
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Magros\Encryptable\Encryptable; class User extends Model { use Encryptable; /** * The attributes that should be encrypted when stored. * * @var array */ protected $encryptable = [ 'email', 'address' , 'name']; /** * Optionally you can define the attributes that should be converted to camelcase when retrieve. * * @var array */ protected $camelcase = ['name']; }
-
可选。加密当前数据
如果你在数据库中当前有数据,可以使用
php artisan encryptable:encryptModel 'App\User'
命令来加密它。此外,你可以使用
php artisan encryptable:decryptModel 'App\User'
命令来解密它。注意:你必须首先实现
Encryptable
特质并设置$encryptable
属性 -
如果你在使用带有加密值的 exists 和 unique 规则,请用 exists_encrypted 和 unique_encrypted 替换它们
$validator = validator(['email'=>'foo@bar.com'], ['email'=>'exists_encrypted:users,email']);
-
你仍然可以使用
where
函数$validator = User::where('email','foo@bar.com')->first();
自动将
foo@bar.com
加密,并将其传递给查询构建器。