laravel-database-encryption icon indicating copy to clipboard operation
laravel-database-encryption copied to clipboard

orderByEncrypted functionality

Open luckyhanna opened this issue 2 years ago • 0 comments

Besides the where clauses, and orderBy would also be useful. In order to be able to sort the data by encrypted fields, I extended the EloquentBuilder class and added the following code:

class CustomEloquentBuilder extends EncryptionEloquentBuilder
{
    public function orderByEncrypted($column, $direction = 'asc') {
        $salt = substr(hash('sha256', env('APP_KEY')), 0, 16);
        return self::orderByRaw("CONVERT(AES_DECRYPT(FROM_bASE64(`{$column}`), '{$salt}') USING utf8mb4) {$direction}");
    }
}
trait CustomEncryptedAttribute
{
    use EncryptedAttribute;

    public function newEloquentBuilder($query)
    {
        return new CustomEloquentBuilder($query);
    }
}

It would be great to have it as a built-it function in the package.

luckyhanna avatar May 31 '22 13:05 luckyhanna