Skip to content

Instantly share code, notes, and snippets.

@liyu001989
Last active September 19, 2019 02:37
Show Gist options
  • Save liyu001989/813b0c5ab8c04e06e8404b21a17cf46e to your computer and use it in GitHub Desktop.
Save liyu001989/813b0c5ab8c04e06e8404b21a17cf46e to your computer and use it in GitHub Desktop.
HashIdHelper
<?php
namespace App\Models\Traits;
use Hashids;
trait HashIdHelper
{
private $hashId;
public function getHashIdAttribute()
{
if (!$this->hashId) {
$this->hashId = Hashids::connection(self::getHashIdConnection())->encode($this->id);
}
return $this->hashId;
}
// 先将参数 decode 为模型id,再调用父类的 resolveRouteBinding 方法
public function resolveRouteBinding($value)
{
$value = $this->decodeHashId($value);
if (!$value) {
return;
}
return parent::resolveRouteBinding($value);
}
public static function decodeHashId($hashId)
{
return current(Hashids::connection(self::getHashIdConnection())->decode($hashId));
}
public function scopeWhereHashId($query, $hashId)
{
return $query->where('id', $this->decodeHashId($hashId));
}
// 使用 hash_id 生成 URL
public function getRouteKey()
{
return $this->hash_id;
}
protected static function getHashIdConnection()
{
$connection = defined('static::HASHID_CONN')
? static::HASHID_CONNECTION
: \Str::snake(class_basename(self::class));
return config()->has('hashids.connections.'.$connection)
? $connection
: config('hashids.default');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment