Encoding and Decoding laravel model attributes made easy.
- minimum php version : 7.1.0
composer require ajangi/laravel-crypt-model
To register your models, you should pass the desired prefix and the class name of your model to.
<?php
use LaravelCryptModel\PrefixedAttributes;
PrefixedAttributes::registerModels([
'user' => [
'model' => \App\Models\User::class,
'attributes' => ['id','avatar_file_id']
],
'Order' => [
'model' => \App\Models\Oredr::class,
'attributes' => ['id','customer_user_id']
]
]);
Typically, you would put the code above in a service provider.
php artisan vendor:publish --provider="LaravelCryptModel\LaravelCryptoModelServiceProvider"
then select ajangi/laravel-crypt-model to push config file. After publishing the file config/laravel-crypt-model.php
will be added.
<?php
return [
'model_new_attribute_prefix' => 'hashed_',
'aes_secret_key' => env('AES_SECRET_KEY','6818f23eef19d38dad1d272345454549991f6368'), //the secret key you should change
'aes_secret_iv' => env('AES_SECRET_IV','73658734657823465872364587634876523487657'), //the secret iv you should change
];
On each model that needs a hashed prefixed attribute, you should use the LaravelCryptModel\Models\Concerns\HasHashedPrefixedAttributes trait.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use LaravelCryptModel\Models\Concerns\HasHashedPrefixedAttributes;
class User extends Model
{
use HasFactory,Notifiable, HasHashedPrefixedAttributes;
}
<?php
use App\Models\User;
$user = User::query()
->where('name','Alireza')
->first();
return json_encode($user);
the above code will return :
{
"id": 1,
"name": "Alireza",
"family": "Jangi",
"mobile": "09393563537",
"created_at": null,
"updated_at": null,
"user_id_hashed_": "user_id_hashed_7QOG8YaqVQigyD0sYEd25A==",
}
To get model using prefixed hashed attribute you can try two methods :
use App\Models\User;
$user = User::findByPrefixedAttribute('user_id_hashed_7QOG8YaqVQigyD0sYEd25A=='); // the prefixed hashed value we get in step 4
return json_encode($user);
the above code will return :
{
"id": 1,
"name": "Alireza",
"family": "Jangi",
"mobile": "09393563537",
"created_at": null,
"updated_at": null,
"user_id_hashed_": "user_id_hashed_7QOG8YaqVQigyD0sYEd25A==",
}
use LaravelCryptModel\PrefixedAttributes;
$user = PrefixedAttributes::findModel('user_id_hashed_7QOG8YaqVQigyD0sYEd25A=='); // the prefixed hashed value we get in step 4
return json_encode($user);
the above code will return :
{
"id": 1,
"name": "Alireza",
"family": "Jangi",
"mobile": "09393563537",
"created_at": null,
"updated_at": null,
"user_id_hashed_": "user_id_hashed_7QOG8YaqVQigyD0sYEd25A==",
}
Take a look at CONTRIBUTING for details.