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.
Thanks man! It really helps.
However, I have one little question. I get an error when I'm trying to use where statically.
So just for an example:
Would give me an error with: