--- tags: PHP, Laravel, Backend --- # Laravel哈希數據ID ## 為甚麼需要hash ID 在專案中,我們數據的ID通常是自行增加的,如使用Url get 的參數是商品ID會造成以下問題 1. 數據的ID是公開的,不希望對外暴露有規則索引 1. 防止爬蟲侵擾 1. 容易根據 ID 猜測數專案中的商品數量 1. 隨著數據的增長,ID 會越來越大,無法統一長度 這時後就可以靠hash id來加密解決問題,還有很多種解決方案,例如使用UUID,使用自己的邏輯創建新的id欄位,今天來介紹一個簡單的解決方案是基於[hashids/hashids](https://github.com/vinkla/hashids)項目[vinkla/hashids](https://github.com/vinkla/laravel-hashids) ## 安裝 `composer require vinkla/hashids` 我是使用laravel7在安裝過程中報錯, 有遇到此問題的小夥伴可以安裝看看版本8.0.0試試 `composer require vinkla/hashids ^8.0.0` 安裝成功後需要將 vinkla/hashids 的配置文件發佈出來 `php artisan vendor:publish --provider="Vinkla\Hashids\HashidsServiceProvider"` ## 調整配置 到`config\hashids.php`調整參數 更改salt,可以為目標數字增加變量,確保他人沒有相同的salt情況下,無法轉換回數字 更改length,可以指定轉換後的字符串最小長度 vinkla/hashids 是透過對數字進行編碼形成字符串,當然也可以對編碼過的字符串進行解碼,達成加密數據ID的效果 ```php= 'connections' => [ 'main' => [ 'salt' => 'example', 'length' => '6', ], 'alternative' => [ 'salt' => 'your-salt-string', 'length' => 'your-length-integer', ], ], ``` ## 基本範例 可以使用`php artisan tinker`在shell中嘗試 In shell ```shell >>> Hashids::encode(1); => "E6R3Qg" >>> Hashids::decode("E6R3Qg"); => [ 1, ] ``` In controller ```php= use Vinkla\Hashids\Facades\Hashids; Hashids::encode(1); // 生成E6R3Qg Hashids::decode('E6R3Qg'); // 解碼後得到數組 [1] ``` ### 更換不同連接規則 如更改後找不到連接器,清除config cache,`php artisan config:cache` ```php= // 使用alternative的配置encode Hashids::connection('alternative')->encode($id); // 使用alternative的配置decode Hashids::connection('alternative')->decode($id); ``` ### 更改預設連接 預設是使用`main`的配置 ```php= Hashids::getDefaultConnection(); // 會回傳 main. ``` 可以使用以下方法更改預設連接 ```php= Hashids::setDefaultConnection('alternative'); // 此時預設會變成 `alternative`. ``` ## 使用情境 我是使用在model,增加一個hashid的欄位,假如model名為Store,就可以使用`Store::find(1)->hashid`取得ID是1的store hashid ```php= protected $appends = array('hashid'); public function getHashidAttribute() { return Hashids::encode($this->id); } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up