intervention / eloquent-hashid
Laravel Eloquent 模型配置 HashId 特性
2.0.0
2023-08-01 10:53 UTC
Requires
- php: ^8.0
- hashids/hashids: ^5
README
此包提供了一种特性,用于轻松地在您的 Eloquent 模型中编码和解码hashids。每个模型都获得一个属性和一个用于 hashid 查询的作用域。
安装
您可以使用 Composer 安装此包。
通过 Composer 需求此包
$ composer require intervention/eloquent-hashid
Laravel 将自动发现包的服务提供者类。
设置
安装后,您可以使用以下命令将配置文件发布到您的 Laravel 应用程序。
$ php artisan vendor:publish --provider="Intervention\EloquentHashid\Laravel\EloquentHashidServiceProvider"
您将在 config/hashid.php
中找到一个新配置文件,您可以对其进行自定义。我强烈建议至少将 salt_prefix
选项更改为您自己的值。
现在,您可以在您的 Eloquent 模型 中包含 Intervention\EloquentHashid\HasHashid
特性,以添加 hashid 功能。
use Intervention\EloquentHashid\HasHashid; class Item extends Model { use HasHashid; }
用法
代码示例
每个 Eloquent 模型都获得一个新的 hashid
属性,该属性基于模型的类名、键和盐前缀创建。您还可以使用现在添加的 hashid()
作用域查询模型。
访问 hashid 属性
$item = App\Models\Item::find(123); // access hashid attribute $hashid = $item->hashid
查询模型
// query model with scope $item = App\Models\Item::hashid('Ma93ka')->firstOrFail(); // scope can also select multiple items by array $item = App\Models\Item::hashid(['Ma93ka', 'Op92ae'])->get(); // scope query in one call $item = App\Models\Item::findByHashid('Ma93ka'); // scope query in one call, throw exception if no model was found $item = App\Models\Item::findByHashidOrFail('Ma93ka');
路由模型绑定
Eloquent 模型可以通过定义自定义键在路由中通过它们的 hashid 进行解析。
use App\Models\Item; Route::get('/items/{item:hashid}', function (Item $item) { return $item; });
作者
此库由 Oliver Vogel 开发和维护。
许可
Intervention Eloquent HashID 在 MIT 许可证 下授权。