matt-daneshvar/eloquent-hashids

自动生成并持久化新创建的Eloquent模型中的Hashids。

v1.0.0 2019-06-26 14:49 UTC

This package is auto-updated.

Last update: 2024-09-14 17:43:03 UTC


README

Build Status GitHub

使用Ivan Akimov的Hashids库自动在您新创建的Eloquent模型上持久化Hashids。

当您需要生成唯一的字母数字(或任何其他字符)组合来表示您的模型时,这可能非常有用。

安装

使用composer安装此包。

composer require matt-daneshvar/eloquent-hashids

使用

在您的迁移中数据库表中添加一个可空的 hashid列。

$table->string('hashid')->nullable();

使用Hashid特性自动生成和持久化您的新模型的Hashids。可选地使用HashidRouting将您的模型设置为使用Laravel的路由模型绑定hashid列。

use Illuminate\Database\Eloquent\Model;
use MattDaneshvar\EloquentHashids\Hashid;
use MattDaneshvar\EloquentHashids\HashidRouting;

class Receipt extends Model
{
    use Hashid, HashidRouting;
}

自定义Hashid生成

虽然该包尝试使用合理的默认值来最小化开箱即用的配置,但您仍然可以自由地通过在模型定义上的静态属性来调整Hashid生成行为。

class Receipt extends Model
{
    use Hashid;
    
    /**
     * The column used to store Hashid.
     *
     * @var array
     */
    protected static $hashidColumn = 'hashid';
    
    /**
     * The minimum length of the generated Hashids.
     *
     * @var array
     */
    protected static $hashidMinLength = 8;
    
    /**
     * The whitelist of characters used inside the generated Hashids.
     *
     * @var array
     */
    protected static $hashidChars = 'abcdefghijklmnopqrstuvwxyz1234567890';
    
    /**
     * The salt for generating Hashids.
     *
     * @var array
     */
    protected static $hashidSalt = 'your unique salt';
    
    /**
     * The attribute encoded to generate the Hashid.
     *
     * @var array
     */
    protected static $hashidKey = 'id';
}

更改Hashid列

要自定义hashid列,请在您的模型上设置自定义的$hashidColumn值。

class Receipt extends Model
{
    use Hashid;
    
    protected static $hashidColumn = 'uid';
}

更改盐值

每个模型的表名默认用作生成Hashids的盐。因此,具有相同ID的类(例如,ID为1的Task模型和ID为1的Receipt模型)将具有不同的Hashids。您可以通过指定模型上的$hashidSalt来更改此行为并覆盖盐值。

class Receipt extends Model
{
    use Hashid;
    
    protected static $hashidSalt = 'salt and pepper';
}

创建自己的Hashids实例

为了完全自定义底层Hashids库的行为,您还可以在模型的生命周期方法中定义自己的Hashids实例。请注意,您的Hashids实例将优先于所有其他自定义设置,因此一旦指定了您自己的Hashids实例,您的模型上所有其他静态Hashid属性(即$hashidMinLength$hashidChars等)都将被忽略。

class Receipt extends Model
{
    public static function boot()
    {
        parent::boot();
    
        static::$hashidsInstance = new Hashids('salt and pepper', 5);
    }
}

使用HashidRouting特性

Hashids与Eloquent模型的一个常见用例是使用生成的Hashids作为标识符的短URL。

例如,您可能希望使用它们的Hashid值来表示您的应用程序的收据

https://example.com/receipts/2ov7j3o3

而不是它们的ID

https://example.com/receipts/4

为了更方便,这个包自带了一个HashidRouting特性;一旦添加到您的模型中,这个特性就会更改模型的路由键名称为对应的Hashid列,这将允许您利用Laravel的路由模型绑定并使用Hashid URL。

Route::get('api/receipts/{receipt}', function (App\Receipt $receipt) {
    return $receipt->total;
});

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。