本指南解釋如何實現加密和解密 Laravel 模型中的敏感資料。透過執行以下步驟,您可以 在將資料儲存到資料庫之前對其進行保護,並在儲存時對其進行解密 正在檢索它。
先決條件
- Laravel:確保您使用的是 Laravel 專案。
- 加密金鑰:Laravel 在 .env 檔案中自動產生 APP_KEY。此金鑰由 Laravel 的加密服務使用。
第 1 步:在模型中設定加密
在模型中,我們將使用 Laravel 的 encrypt() 和 decrypt() 函數自動處理指定欄位的加密和解密。
Doctor模型
使用加密和解密方法建立或更新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); }}
說明
- Setter 方法:使用 set{AttributeName }Attribute() 在資料儲存到資料庫之前加密資料。
- Getter 方法:從資料庫擷取資料時,使用 get{AttributeName}Attribute() 解密。
第 2 步:資料儲存與擷取的控制器
在控制器中,您可以處理驗證並呼叫模型的 直接加密屬性,無需額外加密/解密 步驟。
DoctorController
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); }}
說明
- register 方法:驗證傳入的請求,建立新的醫生記錄,並根據模型的加密方法自動加密名字、姓氏、電子郵件和手機等欄位。
- show 方法:透過 ID 檢索醫師記錄。這 模型的 getter 方法之前會自動解密敏感字段 返回數據。
步驟 3:資料庫設定
確保敏感資料的 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();});
注意:由於加密值可能比明文長得多值,因此加密欄位首選文字。
步驟 4:處理解密異常
為了增強錯誤處理,請將解密邏輯包裝在模型 getter 的 try-catch 區塊中:
<?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); }}
附加說明
- 環境安全:確保 APP_KEY 安全地儲存在 .env 檔案中。此密鑰對於加密/解密至關重要。
- 資料備份:如果資料完整性至關重要,請確保您有備份機制,因為沒有正確的 APP_KEY,加密資料將無法復原。
摘要
- 模型加密:儲存前使用setter方法加密數據,檢索時使用getter方法解密。
- 控制器邏輯:控制器可以直接處理加密字段,無需額外的加密代碼.
- 資料庫配置:使用 TEXT 或 LONGTEXT 欄位作為加密欄位。
- 安全注意事項:保護您的 APP_KEY 並在 getter 中使用異常處理來處理解密錯誤。
以上是Laravel 中的資料加密與解密的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境