Laravel Eloquent - Encrypting/Decrypt Data on call

后端 未结 2 1997
轻奢々
轻奢々 2021-02-07 11:29

I can use Crypt to encrypt/decrypt my data. I want to encrypt some information in my db (such as the name, email, phone number to name a few).

Assuming that

相关标签:
2条回答
  • 2021-02-07 12:13

    It doesn't really make sense to encrypt everything. For example, you never want to encrypt the primary key; that doesn't even make sense. Likewise you probably don't want to encrypt the date fields; you'll lose the ability to perform any sort of SQL query on them.

    With that in mind, you can try something like this:

    class BaseModel extends Eloquent {
    
        protected $encrypt = [];
    
        public function setAttribute($key, $value)
        {
            if (in_array($key, $this->encrypt))
            {
                $value = Crypt::encrypt($value);
            }
    
            return parent::setAttribute($key, $value);
        }
    
        public function getAttribute($key)
        {
            if (in_array($key, $this->encrypt))
            {
                return Crypt::decrypt($this->attributes[$key]);
            }
    
            return parent::getAttribute($key);
        }
    
        public function attributesToArray()
        {
            $attributes = parent::attributesToArray();
    
            foreach ($attributes as $key => $value)
            {
                if (in_array($key, $this->encrypt))
                {
                    $attributes[$key] = Crypt::decrypt($value);
                }
            }
    
            return $attributes;
        }
    
    }
    

    then have all you models extend this one, and set the $encrypt property to whatever columns you want encrypted for that particular model.


    P.S. If you want to use Eloquent's accessor functionality, you'll have to play with this a bit more.

    0 讨论(0)
  • 2021-02-07 12:14

    It's worth mentioning Elocrypt library for Laravel 4. It's a more elaborate solution that works the same way. If you're using Laravel 5 use this one instead: Elocrypt 5.

    0 讨论(0)
提交回复
热议问题