Turns a model binding from /profile/1
to /profile/XDBoYzYE
just by using a trait.
This trait is based on laravel-hashids, require it first using composer. Then just copy paste the trait below somewhere in your laravel project.
To use the encoded version of model's id
just use the trait like:
<?php
// ...
class User extends Authenticatable
{
use HashidsRoutable;
// ....
}
To use another attribute rather then id
override the getRouteHashKeyName()
method:
<?php
// ...
class User extends Authenticatable
{
use HashidsRoutable;
public function getRouteHashKeyName()
{
return 'another_attribute_name';
}
// ....
}
By default the trait will use laravel-hashids's default connection, to change it on a per-model base override the getHashidsConnection()
method:
<?php
// ...
class User extends Authenticatable
{
use HashidsRoutable;
public function getHashidsConnection()
{
return 'alternative';
}
// ....
}
If you don't want to use laravel-hashids (Why shouldn't you?), change the getHashidsInstance()
method to return a new instance of hashids.php:
<?php
// ...
trait HashidsRoutable
{
protected function getHashidsInstance()
{
return new Hashids\Hashids('your-salt', 0, 'abcdefghijklmnopqrstuvwxyz');
}
// ...
Overriding the where()
method of the Model
class might be consider dirty. If you don't like it, use Explicit Binding instead of this trait to build your urls.
@pmochine @hakimihamdan88 I found a solution!
Remove the public function where() from the trait.
Insert
Route::bind('id', function ($id) { return \Hashids::decode($id)[0] ?? $id; });
in app/Providers/RouteServiceProvider.php in the public function boot() section and everything is fine!
I've forked it under https://gist.github.com/abasjo/9fdca139659d60ad56c833495b19098a (quick & dirty).
Hope it helps!