【问题标题】:Using vinkla/hashids package in Laravel 5.2 to obsfucate id's in URL's在 Laravel 5.2 中使用 vinkla/hashids 包来混淆 URL 中的 id
【发布时间】:2016-06-16 12:28:38
【问题描述】:

我已经在 laravel 5.2 上安装并配置了最新版本 (2.3.0) 的vinkla/hashids。

我不确定如何在我的 URL 路由上实现它的功能。

我想混淆显示在我的 URL 路由中的所有 id 属性。

例如 - http://localhost:8000/profile/3/edit 应该变成 http://localhost:8000/profile/xyz/edit

我已尝试通过将其添加到 App\Profile.php 来覆盖 Illuminate\Database\Eloquent\Model.php 上的以下方法-

public function getRouteKey()
{
dd('getRouteKey method');
    return Hashids::encode($id);
}

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

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

谢谢

【问题讨论】:

标签: php laravel-5.2 hashids


【解决方案1】:

这是我为同样的问题所做的:

说你的路线有

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);
}

【讨论】:

  • 我不想使用显式绑定,我想知道如何在一些隐式绑定中做到这一点...
  • @CaioKawasaki 这也需要在数据库中具有散列字段。你想要吗?
  • 感谢您的回答。我相信更改“getRouteKeyName”值是没有必要的。
猜你喜欢
  • 2016-12-18
  • 2018-09-29
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多