malico / laravel-nanoid
1.1.3
2024-05-09 16:40 UTC
Requires
- hidehalo/nanoid-php: ^1.1
- illuminate/auth: ^8.0|^9.0|^10.0|^11.0
- illuminate/support: ^8.0|^9.0|^10.0|^11.0
Requires (Dev)
- ext-pdo: *
- laravel/pint: ^1.10
- orchestra/testbench: ^8.0|^9.0
- pestphp/pest: ^2.0
README
简介
为你的 Eloquent 模型的 ID 提供 nanoid 支持的简单解决方案。(类似 Stripe 的 ID)
安装
composer require malico/laravel-nanoid
使用方法
在你的模型中使用 nanoid,像这样在模型中使用 trait HasNanoids
。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; + use Malico\LaravelNanoid\HasNanoids; class Book extends Model{ use HasFactory; + use HasNanoids; }
你的迁移文件应该像这样。
// migration file public function up() { Schema::create('test_models', function (Blueprint $table) { - $table->id(); + $table->string('id')->primary(); // $table->timestamps(); }); }
要创建一个新的迁移,使用 artisan 命令 make:nanoid-migration
。所有参数与 make:migration
命令相同。
选项
- 前缀:为了指定 ID 的前缀,你可以在你的模型类中添加 `nanoPrefix` 属性。
- 对于 ID 的长度也适用。
<?php class YourModel Extends \Illuminate\Database\Eloquent\Model { /** @var array|int */ protected $nanoidLength = 10; // id will be of length 10 // specifying to array. e.g [10, 20] will generate id of length 10 to 20 // or public function nanoidLength(): array|int { // [10,20] return 10; } /** @var string */ protected $nanoidPrefix = 'pl_'; // id will look: pl_2k1MzOO2shfwow ... // or public function nanoidPrefix(): string { return 'pay_'; // pay_2MII83829sl2d } /** @var string */ protected $nanoidAlphabet = 'ABC'; // or public function nanoidAlphabet(): string { return 'ABC'; // pay_ACBACB } public function uniqueIds() { // will create nanonids for 'unique_id' &'another_with' // Also, won't break if id is not listed. return ['unique_id', 'another_id']; } }
如果你是从 0.x 升级,请查看升级指南:UPGRADE.MD
作者
Ndifon Desmond Yong