From 539597d535b01a8c95c47307ec6267865408eb46 Mon Sep 17 00:00:00 2001 From: Jonathan Hassall Date: Tue, 3 Oct 2023 08:32:21 +0100 Subject: [PATCH] =?UTF-8?q?Add=20feature=20to=20override=20salt=20(environ?= =?UTF-8?q?ment=20variable/config)=20for=20when=20t=E2=80=A6=20(#98)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add feature to override salt (environment variable/config) for when the same HashIds are required for different projects * add trailing comma. --------- Co-authored-by: Rifki Alhuraibi --- README.md | 4 ++++ config/hashid.php | 5 +++++ src/Repository.php | 4 ++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b99fe67..2a87921 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,10 @@ class User extends Model { ``` +#### Salt + +The salt is generated automatically based on your app key and hash_alphabet. If you need to use the same salt between different projects, you can set the `HASHID_SALT` environment variable. + #### Route binding When HashableId trait is used, base getRouteKey() and resolveRouteBinding() are overwritten to use the HashId as route key. diff --git a/config/hashid.php b/config/hashid.php index 47f5eaa..eb83c5d 100644 --- a/config/hashid.php +++ b/config/hashid.php @@ -10,4 +10,9 @@ * Determine HashId characters set. */ 'hash_alphabet' => env('HASHID_ALPHABET', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), + + /* + * Override generated HashId salt. + */ + 'hash_salt' => env('HASHID_SALT', null), ]; diff --git a/src/Repository.php b/src/Repository.php index dcc1fc0..3e1412a 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -62,13 +62,13 @@ public function get(string $key): Hashids if ($key === 'default') { return $this->make( $key, - substr(config('app.key', config('hashid.hash_alphabet')), 8, 4).substr(config('app.key', 'lara'), -4) + config('hashid.hash_salt') ? config('hashid.hash_salt') : substr(config('app.key', config('hashid.hash_alphabet')), 8, 4).substr(config('app.key', 'lara'), -4) ); } $key = strlen($key) > 4 ? $key : 'default'.$key; - return $this->make($key, substr($key, -4).substr(config('app.key', 'lara'), -4)); + return $this->make($key, config('hashid.hash_salt') ? config('hashid.hash_salt') : substr($key, -4).substr(config('app.key', 'lara'), -4)); } /** {@inheritdoc} */