我已经在laravel 5.2上安装并配置了最新版本(2.3.0)的vinkla/hashids。
我不确定如何在我的URL路由上实现它的功能。
我想要模糊显示在我的URL路由中的所有id属性。
例如,- http://localhost:8000/profile/3/edit应该变成http://localhost:8000/profile/xyz/edit。
我已经尝试在Illuminate\Database\Eloquent\Model.php上覆盖以下方法,将其作为so添加到App\Profile.php -
public function getRouteKey()
{
dd('getRouteKey method');
return Hashids::encode($id);
}我的dd没有显示,所以我没有正确覆盖它。
请您建议我应该如何正确地实现此功能?
谢谢
发布于 2017-01-16 21:50:57
下面是我为同样的问题所做的工作:
假设你的路线有
Route::get('/profile/{profile}', 'ProfileController@showProfile');然后在模型中:
// Attribute used for generating routes
public function getRouteKeyName()
{
return 'hashid';
}
// Since "hashid" attribute doesn't "really" exist in
// database, we generate it dynamically when requested
public function getHashidAttribute()
{
return Hashids::encode($this->id);
}
// For easy search by hashid
public function scopeHashid($query, $hashid)
{
return $query->where('id', Hashids::decode($hashid)[0]);
}最后需要绑定路由参数"profile“。你必须先解码它,然后在数据库中搜索(默认绑定不起作用)。因此,在app/Providers/RouteServiceProvider.php中
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
Route::bind('profile', function($hashid, $route) {
try {
return Profile::hashid($hashid)->first();
}
catch (Exception $e) {
abort(404);
}
});
parent::boot($router);
}https://stackoverflow.com/questions/37859263
复制相似问题