首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Laravel 5.2中使用vinkla/hashids包模糊URL中的id

在Laravel 5.2中使用vinkla/hashids包模糊URL中的id
EN

Stack Overflow用户
提问于 2016-06-16 20:28:38
回答 1查看 1.9K关注 0票数 3

我已经在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 -

代码语言:javascript
复制
public function getRouteKey()
{
dd('getRouteKey method');
    return Hashids::encode($id);
}

我的dd没有显示,所以我没有正确覆盖它。

请您建议我应该如何正确地实现此功能?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2017-01-16 21:50:57

下面是我为同样的问题所做的工作:

假设你的路线有

代码语言:javascript
复制
Route::get('/profile/{profile}', 'ProfileController@showProfile');

然后在模型中:

代码语言:javascript
复制
// 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

代码语言:javascript
复制
/**
 * 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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37859263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档