Reputation: 146
I have installed and configured the latest version (2.3.0) of vinkla/hashids on laravel 5.2.
I'm unsure how to implement its functionality on my URL routes.
I want to obsfucate all id attributes which are displayed in my URL routes.
For example- http://localhost:8000/profile/3/edit should become http://localhost:8000/profile/xyz/edit.
I have tried overriding the following method on Illuminate\Database\Eloquent\Model.php by adding it to App\Profile.php as so-
public function getRouteKey()
{
dd('getRouteKey method');
return Hashids::encode($id);
}
My dd is not displaying so I'm not overriding it correctly.
Please can you advise how I should implement this functionality correctly?
Thanks
Upvotes: 4
Views: 2140
Reputation: 9771
Here's what I have been doing for the same problem:
Say your routes has
Route::get('/profile/{profile}', 'ProfileController@showProfile');
Then in model:
// 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]);
}
Finally you need to bind the route parameter "profile". You have to decode it first, then search in database (default binding won't work). So, in 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);
}
Upvotes: 4