Using Hashid with Laravel 5
Hashid can be used to to obfuscate id for the url of the web pages. Sometimes we want to prevent the id display for security reasons. Tonight I was working on it so thought to share my experience.
Hashid is a php open-source library which generates ids like Youtube ids where the numeric id is being converted to alphabets. Example 123 converted to bnt.
I have used this Laravel 5 wrapper for my project which can be installed via composer.
composer require vinkla/hashids
I have used it to hide the users id so that no one else can use it to edit others account. In user model I have added getRouteKey() method.
User.php
public function getRouteKey() { return Hashids::encode($this->getKey()); }
getRouteKey[Name] are implementation of the interface, which lets you create routes like before route(‘users.show’, $user->id) or easier route(‘users.show’, $user). Eloquent objects can be passed as route parameters and Laravel will to the job.
In the controller the id will be passed as obfuscated id therefore we need to decode it before passing the data to database or apply the business logic. Route binding is the easiest way of achieving this.
Routes.php
Route::bind('users', function($user) { return Hashids::decode($user); });
The userid is being decoded before it is being passed to the controller.
index.blade.php
Laravel does the job to fetch the userid from this.
<a href="{{ route('show_user', [$user]) }}">
Another method:
In the model
protected $appends = ['hashid'];
public function getHashidAttribute()
{
return Hashids::encode($this->attributes['id']);
}