这是我为同样的问题所做的事情:
说你的路线有
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);
}