io238/eloquent-encoded-ids

使用 Hashids (简短、唯一、非顺序 ID) 为 Laravel Eloquent 实现自动路由键加密,支持前缀

1.0.1 2022-03-21 16:57 UTC

This package is auto-updated.

Last update: 2024-09-21 22:20:12 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

使用 Hashids (简短、唯一、非顺序 IDs) 为 Laravel Eloquent 实现自动路由键加密,并支持前缀。

背景

默认情况下,Laravel 使用数字、顺序 ID 作为模型。这些数字 ID 也被用作 路由键

route('users.show', User::find(1)) // http://app.test/user/1
route('users.show', User::find(2)) // http://app.test/user/2
route('users.show', User::find(3)) // http://app.test/user/3

此包自动编码模型 ID,以确保序列不会对外公开

route('users.show', User::find(1)) // http://app.test/user/m8y78
route('users.show', User::find(2)) // http://app.test/user/p8b7v
route('users.show', User::find(3)) // http://app.test/user/dvd6v

这对于隐藏敏感应用程序信息很有用(例如,用户总数、发票等)。

安装

您可以通过 composer 安装此包

composer require io238/eloquent-encoded-ids

用法

为了编码 Laravel 模型的 ID,只需将 HasEncodedIds 特性添加到模型中即可

namespace App\Models;

use Io238\EloquentEncodedIds\Traits\HasEncodedIds;

class User extends Model {

    use HasEncodedIds;

    // ..

}

内部,Laravel 仍将在控制器中使用数字 ID,并在数据库中以数字 ID 存储它们

class UserController extends Controller {

    public function show(User $user)
    {
        return $user->id; // 1
    }
}

前缀

默认情况下,此包会在编码 ID 中添加前缀,这有助于识别已编码的 ID 类型。

示例: User 模型的编码 ID 以 u_ 开头,例如 u_m8y78

它使用模型名称的首字母,或者您可以显式提供作为模型受保护属性的前缀

class User extends Model {

    use HasEncodedIds;

    protected $prefix = 'usr';

}

配置

此包默认情况下即可使用。不过,您可以通过以下方式发布并自定义配置文件:

php artisan vendor:publish --provider="\Io238\EloquentEncodedIds\EncodedIdsProvider" --tag="config"

这是默认配置文件的默认内容

return [

    // Minimum length of encoded IDs
    'length'           => 5,

    // Alphabet to be used to generate encoded IDs
    // By default this list excludes ambiguous characters
    'alphabet'         => '123456789abcdefghikmnpqrstuvwxyz',

    // Ignore uppercase/lowercase for encoded IDs
    'case-insensitive' => true,

    // Encryption salt
    // Warning: changing the salt, will produce different encoded IDs
    'salt'             => env('APP_KEY'),

    // Use a prefix to the encoded ID, to be able to recognize the model that the ID belongs to
    'prefix'           => true,

    // Character used to separate the prefix from the encoded ID
    'separator'        => '_',

];

测试

composer test

贡献

有关详细信息,请参阅 CONTRIBUTING

安全漏洞

请查看有关如何报告安全漏洞的 安全策略

鸣谢

许可

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