2017-06-25 02:20:24 +08:00
|
|
|
<?php
|
|
|
|
|
2017-08-13 01:24:00 +08:00
|
|
|
namespace App\Models\Traits;
|
2017-06-25 02:20:24 +08:00
|
|
|
|
2017-08-24 23:51:47 +08:00
|
|
|
use Hashids\Hashids;
|
|
|
|
|
2017-12-13 02:43:58 +08:00
|
|
|
trait HashId
|
2017-06-25 02:20:24 +08:00
|
|
|
{
|
2018-01-02 03:48:02 +08:00
|
|
|
/**
|
|
|
|
* @return string
|
|
|
|
* @throws \Hashids\HashidsException
|
|
|
|
*/
|
|
|
|
protected static function createNewHashId()
|
|
|
|
{
|
|
|
|
$hashids = new Hashids('', 12);
|
|
|
|
$mt = str_replace('.', '', microtime(true));
|
|
|
|
return $hashids->encode($mt);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Register callbacks
|
|
|
|
*/
|
2017-06-25 02:20:24 +08:00
|
|
|
protected static function boot()
|
|
|
|
{
|
|
|
|
parent::boot();
|
2018-01-02 03:48:02 +08:00
|
|
|
static::creating(function ($model) {
|
2018-01-30 08:14:55 +08:00
|
|
|
if (empty($model->id)) {
|
|
|
|
$model->id = static::createNewHashId();
|
2017-06-25 02:20:24 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|