LingxiTeam / laravel-hashids by RryLee

A Hashids bridge for Laravel
2,911
18
4
Package Data
Maintainer Username: RryLee
Package Create Date: 2017-03-19
Package Last Update: 2018-11-08
Language: PHP
License: MIT
Last Refreshed: 2024-11-14 15:10:21
Package Statistics
Total Downloads: 2,911
Monthly Downloads: 8
Daily Downloads: 1
Total Stars: 18
Total Watchers: 4
Total Forks: 0
Total Open Issues: 0

Laravel Hashids

Latest Stable VersionTotal DownloadsLicense

安装

composer require lingxi/hashids

添加到 app.php

Lingxi\Hashids\HashidsServiceProvider::class
'Hashids' => Lingxi\Hashids\Facades\Hashids::class

Config

php artisan vendor:publish --provider='Lingxi\Hashids\HashidsServiceProvider'
<?php

return [

    'default' => 'main',

    'middleware' => [
        'open' => true,

        // 路由中需要被 decode 的 id
        'route_parameters' => [
            //
        ],

        // 请求参数需要被 decode 的 id
        'request_parameters' => [
            //
        ]
    ],

    // 开启严格模式之后,解密 id 错误会抛出异常
    'strict' => [
        'enable' => true,
        'default' => 0,
    ],

    'connections' => [

        'main' => [
            'prefix' => '',
            'salt' => 'your-salt-string',
            'length' => 'your-length-integer',
            'alphabet' => 'your-alphabet-string',
        ],

    ],

];

Middleware

添加中间件

如果是全局中间件,那么对 route 参数是无法自动 decode 的

\Lingxi\Hashids\Middleware\DecodePublicIdMiddleware::class,

在 config/hashids.php 中去配置需要解密的路由参数以及请求参数

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Lingxi\Hashids\ModelTraits\PublicId;

class Post extends Model
{
    use PublicId;

    public function comments()
    {
        return $this->morphMany(\App\Comment::class, 'commentable');
    }
}

Then, get public id.

Post::first()->public_id

Debug

php artisan id:en 1 --uri=p

php artisan id:de sdfghjkla;sdjhasjhdfgahjsdjasd