balping/laravel-hashslug
Composer 安装命令:
composer require balping/laravel-hashslug
包简介
Package providing a trait to use Hashids on a model
README 文档
README
This package is useful to hide real model ids in urls using Hashids. A hashid (slug) is deterministically generated given an application, a model class and an id. Also, given a hashid (slug), the real id can be decoded. Thus no extra field needs to be stored in the database, ids are decoded on each request.
Generates urls on the fly
database -> id (1) -> hashslug (K4Nkd) -> url (http://localhost/posts/K4Nkd)
Decodes hashids and finds models on the fly
url (http://localhost/posts/K4Nkd) -> hashslug (K4Nkd) -> id (1) -> database -> model
Hashslugs have the following properties:
- It is guaranteed that hashslugs are unique per id
- It is guaranteed that for different models, different series of hashslugs are generated (a post of id 1 will have a different hashslug as a comment with id 1)
- It is guaranteed that for different installations, different series of hashslugs are generated (depending on app key in the
.envfile)
It is important to note that hashids are not random, nor unpredictable. Do not use this package if that's a concern. Quoting from hashids.org:
Do you have a question or comment that involves "security" and "hashids" in the same sentence? Don't use Hashids.
However, although hashslug encoding depends on the app key, it cannot be exposed by an attacker, since it's sha256 hashed before passing it to Hashids. Your app key is safe.
Installation
composer require balping/laravel-hashslug
Versions
| Laravel | Hashslug |
|---|---|
| 5.4.* | 2.0.* |
| 5.5 - 5.8 | 2.1.* |
| 6.* | 2.1.* |
| 7.* | 2.2.* |
| 8.* | 2.3.* |
| 9.* | 2.3.* |
| 10.* | 2.3.* |
| 11.* | 2.3.* |
| 12.* | 2.3.* |
| 13.* | 2.3.* |
Note: This package requires either the BC Math or GMP extension in order to work.
Usage
Include trait on a model that you wish to have hashid slugs to hide numeric incremental ids.
use Illuminate\Database\Eloquent\Model;
use Balping\HashSlug\HasHashSlug;
class Post extends Model {
use HasHashSlug;
}
After this, functions slug(), findBySlug($slug) and findBySlugOrFail($slug) are added to your model.
Every time you generate a url using Laravel's helpers, instead of numeric ids, hashids are used (with the default length of 5 characters):
// routes/web.php
Route::resource('/posts', 'PostController');
// somewhere else
$post = Post::first();
echo action('PostController@show', $post);
// prints http://localhost/posts/K4Nkd
Then you can resolve the model by the slug.
// app/Http/Controllers/PostController.php
public function show($slug){
$post = Post:findBySlugOrFail($slug);
return view('post.show', compact('post'));
}
You can use implicit model binding too. You don't have to do anything, it works automatically!
Just typehint models and they are automatically resolved:
// routes/web.php
Route::resource('/posts', 'PostController');
// app/Http/Controllers/PostController.php
public function show(Post $post){
return view('post.show', compact('post'));
}
If you need explicit model binding, that's also convenient:
//app/Providers/RouteServiceProvider.php
public function boot(){
parent::boot();
Route::model('article', App\Post::class);
}
// routes/web.php
Route::resource('/articles', 'PostController');
// app/Http/Controllers/PostController.php
public function show(Post $post){
return view('post.show', compact('post'));
}
Usage with normal IDs in URLs
In case you want to avoid implicit or explicit model binding with hashslug and want to use the normal ID as default key, that is also possible:
// routes/web.php
Route::resource('/posts', 'PostController')->parameters([
"posts" => "post:id"
]);
// or
Route::get('/posts/{post:id}', [PostController::class, 'show']);
// get URL
action('PostController@show', $post);
// app/Http/Controllers/PostController.php
public function show(Post $post){
return view('post.show', compact('post'));
}
In case you don't use typehints in your controller:
// routes/web.php
Route::resource('/posts', 'PostController');
// or
Route::get('/posts/{id}', [PostController::class, 'show']);
// get URL
action('PostController@show', $post->id);
// app/Http/Controllers/PostController.php
public function show($post_id){
$post = Post::findOrFail($post_id);
}
Alternatively you can override the following two methods to achieve the same effect and fall back to normal IDs:
class Post extends Model {
use HasHashSlug;
public function getRouteKeyName(){
return parent::getRouteKeyName();
}
public function getRouteKey(){
return parent::getRouteKey();
}
}
Customisation
Salts
The uniqueness of hashslug series per model and app installation depends on having unique salts.
By default, the salt passed to Hashids depends on the app key defined in .env and the class name of the model.
Application salt
To change the 'application salt', create file config/hashslug.php then add the following code:
<?php
return [
'appsalt' => 'your-application-salt'
];
Keep in mind that you don't have to configure this, but unless you do and your app key is changed, every url having hashslugs in it will change. This might be a problem for example if a user bookmarked such a url.
Model salt
To use a custom model salt instead of the classname:
class Post extends Model {
use HasHashSlug;
protected static $modelSalt = "posts";
}
This might be a good idea to do, if you have several extended classes of the same model and you need hashslugs to be consistent.
Padding
Change the minimum length of a slug (default: 5)
class Post extends Model {
use HasHashSlug;
protected static $minSlugLength = 10;
}
You can set the minimum length of a slug globally too, by adding the following line to config/hashslug.php:
'minSlugLength' => 10
Alphabet
The default alphabet is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
This can be changed:
class Post extends Model {
use HasHashSlug;
protected static $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
You can set the alphabet globally too, by adding the following line to config/hashslug.php:
'alphabet' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Prefix
You can set a custom prefix to hashslug:
class Post extends Model {
use HasHashSlug;
protected static $hashSlugPrefix = 'post-';
}
This would return slugs in the form of post-K4Nkd.
Similar packages and how is this one different
Laravel Hashids
Provides a facade, but no built-in routing. Allows multiple salts through "connections". Unnecessary overhead if you need hashids only for slugging models.
Eloquent-Hashids
Mostly identical to this package in functionality, however by using the above package, it adds an unnecessary layer of complexity. Makes it optional to use route bindings.
Laravel-Hashid
Provides a facade, similar to the above one PLUS a trait similar to this package. No no built-in routing. No tests provided. Unnecessary overhead if you need hashids only for slugging models.
Hashids for Laravel 5
Facade only. Not as good as the first one, since it allows you to have only one salt.
Optimus
Uses different obfuscation method. Facade (and class) only. Nothing related to routing or model traits. It is said to be faster than hashids.
Laravel FakeID
Simliar to this package, but built on Optimus. Facade and trait provided, as well as a special route function. Good tests.
License
This package (the trait and the test file) is licensed under GPLv3.
balping/laravel-hashslug 适用场景与选型建议
balping/laravel-hashslug 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 191.94k 次下载、GitHub Stars 达 24, 最近一次更新时间为 2017 年 08 月 11 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「slug」 「laravel」 「hashids」 「hashid」 「hashslug」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 balping/laravel-hashslug 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 balping/laravel-hashslug 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 balping/laravel-hashslug 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
TitleWithSlugInput - Easy Permalink Slugs for the FilamentPHP Form Builder (PHP / Laravel / Livewire)
Dynamically create a hash of an Eloquent model id value to avoid exposing a record's actual database id.
Hashids for Yii2
Adds slugify twig extensions to your craft install.
A collection of observer classes that can be use in your Laravel application.
A library to extend Object capabilities.
统计信息
- 总下载量: 191.94k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 25
- 点击次数: 17
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: GPL-3.0-only
- 更新时间: 2017-08-11