本指南介绍了如何在 Laravel 模型中实现敏感数据的加密和解密。通过执行以下步骤,您可以在将数据存储到数据库之前保护数据并在检索数据时对其进行解密。

在模型中,我们将使用 Laravel 的 encrypt() 和 decrypt() 函数自动处理指定字段的加密和解密。
使用加密和解密方法创建或更新Doctor模型。我们将在将名字、姓氏、电子邮件和手机等字段保存到数据库之前对其进行加密。
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use IlluminateSupportFacadesCrypt;class Doctor extends Model{
protected $fillable = [
'first_name', 'last_name', 'email', 'mobile', 'hashed_email', 'password'
];
// Automatically encrypt attributes when setting them
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = encrypt($value);
}
public function setLastNameAttribute($value)
{
$this->attributes['last_name'] = encrypt($value);
}
public function setEmailAttribute($value)
{
$this->attributes['email'] = encrypt($value);
}
public function setMobileAttribute($value)
{
$this->attributes['mobile'] = encrypt($value);
}
// Automatically decrypt attributes when getting them
public function getFirstNameAttribute($value)
{
return decrypt($value);
}
public function getLastNameAttribute($value)
{
return decrypt($value);
}
public function getEmailAttribute($value)
{
return decrypt($value);
}
public function getMobileAttribute($value)
{
return decrypt($value);
}}在控制器中,您可以处理验证并调用模型的 直接加密属性,无需额外加密/解密 步骤。
DoctorController 通过验证来处理注册
输入数据,通过模型对其进行加密,并将其保存在数据库中。
获取医生数据时,会自动解密
敏感字段。
<?phpnamespace AppHttpControllers;use IlluminateHttpRequest;use AppModelsDoctor;use IlluminateSupportFacadesHash;class DoctorController extends Controller{
public function register(Request $request)
{
// Validate the incoming request
$validatedData = $request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:doctors,email',
'mobile' => 'required|string|size:10|unique:doctors,mobile',
'password' => 'required|string|min:8|confirmed',
]);
// Hash the email to ensure uniqueness
$hashedEmail = hash('sha256', $validatedData['email']);
// Create a new doctor record (model will handle encryption)
$doctor = Doctor::create([
'first_name' => $validatedData['first_name'],
'last_name' => $validatedData['last_name'],
'email' => $validatedData['email'],
'hashed_email' => $hashedEmail,
'mobile' => $validatedData['mobile'],
'password' => Hash::make($validatedData['password']),
]);
return response()->json([
'message' => 'Doctor registered successfully',
'doctor' => $doctor
], 201);
}
public function show($id)
{
// Fetch the doctor record (model will decrypt the data automatically)
$doctor = Doctor::findOrFail($id);
return response()->json($doctor);
}}确保敏感数据的 doctor 表列的长度足以处理加密数据(通常为 TEXT 或 LONGTEXT)。
迁移设置示例:
Schema::create('doctors', function (Blueprint $table) {
$table->id();
$table->text('first_name');
$table->text('last_name');
$table->text('email');
$table->string('hashed_email')->unique(); // SHA-256 hashed email
$table->text('mobile');
$table->string('password');
$table->timestamps();});注意:由于加密值可能比明文长得多值,加密字段首选文本。
为了增强错误处理,请将解密逻辑包装在模型 getter 的 try-catch 块中:
public function getFirstNameAttribute($value){
try {
return decrypt($value);
} catch (DecryptException $e) {
return null; // Or handle the error as needed
}}以上就是Laravel 中的数据加密和解密的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号