在 Laravel 中加密/解密数据库字段

问题描述 投票:0回答:2

我通过访问器和修改器对 Laravel 中的数据库字段值进行加密/解密,这在正常的雄辩事务中运行良好。

class Person extends Model
{
    use Notifiable;
    protected $table = 'person';

    public function getFirstNameAttribute($value)
    {
        return Crypt::decryptString($value);
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = array();

    protected function user()
    {
        return $this->belongsTo('App\Models\User', 'useraccount_id', 'id');
    }
}

但在以下条件下加密和解密不起作用

  1. 雄辩的关系
  2. 数据库原始查询

工作

$person = Person::find($person_id);
$person->firstName;

不工作

$user = User::find($user_id);
$user->person->firstName;
php laravel encryption laravel-5 eloquent
2个回答
6
投票

你可以使用 laravel 的 Crypt Facades 来做到这一点。 请按照这个例子。

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

$decrypted = Crypt::decryptString($encrypted);

我从本文链接实现:https://hackthestuff.com/article/laravel6-encryption-and-decryption-model-data-using-crypt-class


4
投票

根据 Iman 他的回答,我更改了该特征,因此它可以与 Laravel 自身的强制转换数组一起使用。

<?php
namespace App\Library\Traits;

use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
    /**
     * If the attribute is in the encryptable array
     * then decrypt it.
     *
     * @param  $key
     *
     * @return $value
     */
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (isset($this->casts[$key]) && $value !== '' && !is_null($value) && $this->casts[$key] == 'encrypt') {
            $value = decrypt($value);
        }
        return $value;
    }
    /**
     * If the attribute is in the encryptable array
     * then encrypt it.
     *
     * @param $key
     * @param $value
     */
    public function setAttribute($key, $value)
    {
        if (isset($this->casts[$key]) && $value !== '' && !is_null($value) && $this->casts[$key] == 'encrypt') {
            $value = encrypt($value);
        }
        return parent::setAttribute($key, $value);
    }
    /**
     * When need to make sure that we iterate through
     * all the keys.
     *
     * @return array
     */
    public function attributesToArray()
    {
        $attributes = parent::attributesToArray();
        foreach ($this->casts as $key => $value) {
            if($value == 'encrypt') {
                if (isset($attributes[$key]) && $attributes[$key] !== '' && !is_null($attributes[$key])) {
                    $attributes[$key] = decrypt($attributes[$key]);
                }
            }
        }
        return $attributes;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.