forked from danielpardamean/laravel-mysql-encrypt
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from TapanDerasari/existing-data-encryption-san…
…deep-04-Jan-2024 Existing data encryption
- Loading branch information
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
|
||
## Example of existing data encryption | ||
|
||
```php | ||
<?php | ||
|
||
namespace App\Console\Commands; | ||
|
||
use Illuminate\Console\Command; | ||
use TapanDerasari\MysqlEncrypt\Scopes\DecryptSelectScope; | ||
|
||
|
||
class EncryptionForExistingData extends Command | ||
{ | ||
/** | ||
* The name and signature of the console command. | ||
* | ||
* @var string | ||
*/ | ||
protected $signature = 'encryption-for-existing-data'; | ||
|
||
/** | ||
* The console command description. | ||
* | ||
* @var string | ||
*/ | ||
protected $description = 'Encryption for existing data based on passed model with encryptable fields'; | ||
|
||
/** | ||
* Execute the console command. | ||
*/ | ||
public function handle(): void | ||
{ | ||
|
||
// Put existing models here in which you want to apply encryption | ||
$modelList = ['User']; | ||
foreach ($modelList as $model) { | ||
$modelName = 'App\\Models\\' . $model; | ||
|
||
// Check if the model exists | ||
if (!class_exists($modelName)) { | ||
$this->error("Model '{$modelName}' not found!"); | ||
|
||
return; | ||
} | ||
|
||
// Instantiate the model | ||
$modelObj = new $modelName; | ||
$modelData = $modelObj->withoutGlobalScopes([DecryptSelectScope::class])->get(); | ||
|
||
foreach ($modelData as $modelRecord) { | ||
$updateModel = $modelName::findOrFail($modelRecord->id); | ||
$fields = $updateModel->encryptable; | ||
foreach ($fields as $field) { | ||
$updateModel->$field = $modelRecord->$field; | ||
} | ||
$updateModel->save(); | ||
} | ||
} | ||
|
||
} | ||
} | ||
``` |