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. After that, copy the following code to RouteServiceProvider in the public function boot.
Route::bind('id', function ($id) {
return \Hashids::decode($id)[0] ?? $id;
});
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 Removed the where()
method of the Model
class might be consider dirty.where()
method and added Route::bind. (quick&dirty -> sry ;)
If you don't like it, use Explicit Binding instead of this trait to build your urls.