Open
Description
I would like to create a pull request to add these traits for eloquent models. I would change it a bit to use this lib instead of hashid directly, but you get the idea.
I use these two alot and think it would be great to include them to this lib
HashID.php
/**
* Trait HashID
* @package App\Traits
* @property-read string $hash_id
* @mixin Model
*/
trait HashID
{
public function getHashIdAttribute()
{
return static::idToHash($this->getKey());
}
public static function idToHash($id)
{
return static::newHashId()->encode($id);
}
public static function hashToId($code)
{
$ids = static::newHashId()->decode($code);
$id = empty($ids) ? null : $ids[0];
return $id;
}
/**
* @param $code
* @param array $columns
* @return static
*/
public static function findByHash($code, $columns = null)
{
$id = static::hashToId($code);
return static::find($id, $columns);
}
/**
* @param $code
* @param array $columns
* @return static
*/
public static function findOrFailByHash($code, $columns = null)
{
$id = static::hashToId($code);
return static::findOrFail($id, $columns);
}
public static function newHashId()
{
return new Hashids(config('app.key'), 5, 'qwertyuiopasdfghjklzxcvbnm7894561230');
}
}
HashIDRoutable.php
/**
* Trait HashID
* @package App\Traits
* @mixin \Eloquent
* @mixin HashID
*/
trait HashIDRoutable
{
public function getRouteKeyName()
{
return 'hash_id';
}
public function resolveRouteBinding($value)
{
return (new static)->find(static::hashToId($value));
}
}
Usage
class OrderReturn extends Model
{
use HashID;
use HashIDRoutable; // hash id is used instead of id
}
Metadata
Metadata
Assignees
Labels
No labels