mcris112/laravel-hashidable
Composer 安装命令:
composer require mcris112/laravel-hashidable
包简介
LaravelHashidable - Hashids for Laravel Models and Routes
关键字:
README 文档
README
Laravel Hashidable provides a seamless way to use Hashids in your Laravel models. It automatically handles encoding/decoding of IDs for routing and database lookups, keeping your internal IDs hidden from the public.
This package is an enhanced fork of the original kayandra/hashidable, featuring improved type safety, caching support, global helpers, and fluent query builder integration.
✨ Key Features
- 🛡️ Automatic Route Model Binding: Uses hashids in URLs instead of plain integers.
- 🚀 Performance Caching: Decoded hashids can be cached to improve performance.
- 🛠️ Fluent Scopes: Chainable methods like
whereHashid(),orWhereHashid(), andfindByHashid(). - 🧬 Relation Support: Easily load relations when finding by hashid using
with(). - ✅ Custom Validation: Built-in
hashid_existsrule for validating hashids in requests. - 🌍 Global Helpers: Simple
hashid_encode()andhashid_decode()functions. - 🎨 Customizable: Per-model configuration for salts, lengths, and alphabets.
📥 Installation
composer require mcris112/laravel-hashidable
⚙️ Setup
Add the Hashidable trait to your Eloquent model:
use Mcris112\LaravelHashidable\Hashidable; use Illuminate\Database\Eloquent\Model; class User extends Model { use Hashidable; }
🚀 Usage
Basic Operations
$user = User::find(1); // Accessing the hashid echo $user->hashid; // e.g., "3RwQaeoOR1E7qjYy" // Finding by hashid $user = User::findByHashid("3RwQaeoOR1E7qjYy"); $user = User::findByHashidOrFail("3RwQaeoOR1E7qjYy"); // Decoding manually via model $id = User::hashIdDecode("3RwQaeoOR1E7qjYy"); // 1
Advanced Querying & Relations
Thanks to the new fluent scopes, you can now load relationships while finding by hashid:
// Find with relations (Fluent way) $user = User::with('posts', 'profile')->findByHashid($hashid); // Using whereHashid in complex queries $user = User::whereHashid($hashid) ->where('active', true) ->with('orders') ->firstOrFail(); // Using orWhereHashid $user = User::where('email', 'admin@example.com') ->orWhereHashid($hashid) ->first();
Validation Rule
You can validate that a hashid exists in the database using the hashid_exists rule. This automatically decodes the hashid before checking the database.
use Illuminate\Http\Request; public function update(Request $request) { $request->validate([ 'user_id' => 'required|hashid_exists:App\Models\User,id', ]); }
The rule accepts two parameters:
- The Model class or Table name.
- The Database column (optional, defaults to the model's primary key or
id).
Global Helpers
Decode or encode hashids anywhere without needing a model instance:
// Decode hashid for a specific model class $id = hashid_decode(User::class, "3RwQaeoOR1E7qjYy"); // Encode an ID for a specific model $hash = hashid_encode(User::class, 1);
🔗 Route Model Binding
This package automatically handles Route Model Binding. Instead of IDs, your routes will use hashids:
// routes/web.php Route::get('/users/{user}', [UserController::class, 'show']); // In your controller public function show(User $user) { return view('users.show', compact('user')); }
Generating links automatically uses the hashid:
$url = route('users.show', $user); // /users/3RwQaeoOR1E7qjYy
⚡ Performance Caching
If you find yourself decoding the same hashids frequently, you can enable caching in the config. This will store the decoded integer ID in your cache store.
// config/hashidable.php 'cache' => [ 'enabled' => true, 'ttl' => 86400, // 24 hours ],
🛠️ Configuration
Publish the configuration file:
php artisan vendor:publish --tag=hashidable.config
Global Config (config/hashidable.php)
| Option | Description | Default |
|---|---|---|
salt |
Unique salt for hash generation | env(HASHIABLE_SALT) |
length |
Minimum length of generated hash | 16 |
charset |
Characters used in the hashid | a-zA-Z0-9 |
prefix |
Optional prefix for hashids | "" |
suffix |
Optional suffix for hashids | "" |
separator |
Separator between prefix/suffix | "-" |
Per-Model Configuration
Implement HashidableConfigInterface to customize settings for a specific model:
use Mcris112\LaravelHashidable\HashidableConfigInterface; class Post extends Model implements HashidableConfigInterface { use Hashidable; public function hashidableConfig() { return [ 'length' => 10, 'prefix' => 'post', 'separator' => '_', ]; } }
❓ FAQ
Q: Are hashes stored in the database?
A: No. Hashes are calculated dynamically based on your model's ID and salt.
Q: What happens if I change my salt?
A: All existing hashids will change. It's recommended to set a permanent salt in your .env file (HASHIABLE_SALT).
📄 License
The MIT License (MIT). Please see License File for more information.
mcris112/laravel-hashidable 适用场景与选型建议
mcris112/laravel-hashidable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 179 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 10 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「hash」 「laravel」 「hashids」 「hashidable」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mcris112/laravel-hashidable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mcris112/laravel-hashidable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mcris112/laravel-hashidable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Dynamically create a hash of an Eloquent model id value to avoid exposing a record's actual database id.
Hashids for Yii2
A collection of observer classes that can be use in your Laravel application.
Provides hash tools for Laravel.
Article CSS-ID Frontend Output Optimization
Webman Hashids Used to generate a youtube-like ID from a digital ID
统计信息
- 总下载量: 179
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-10-10