46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Traits\Models;
|
|
|
|
use Carbon\CarbonImmutable;
|
|
use Carbon\CarbonInterface;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
|
use Ramsey\Uuid\Uuid;
|
|
use Symfony\Component\Uid\UuidV7;
|
|
|
|
/** @mixin \Illuminate\Database\Eloquent\Model */
|
|
trait HasUuidV7AsPrimaryKey
|
|
{
|
|
use HasUuids;
|
|
|
|
public function initializeHasUuidV7AsPrimaryKey(): void
|
|
{
|
|
$this->keyType = 'string';
|
|
$this->incrementing = false;
|
|
}
|
|
|
|
public function newUniqueId(): string
|
|
{
|
|
return (string) Uuid::uuid7();
|
|
}
|
|
|
|
public function getCreatedAtColumn()
|
|
{
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @return \Illuminate\Database\Eloquent\Casts\Attribute<\Carbon\CarbonInterface|null,never>
|
|
*/
|
|
protected function createdAt(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn (): ?CarbonInterface => $this->{$this->getKeyName()}
|
|
? CarbonImmutable::instance(UuidV7::fromString($this->{$this->getKeyName()})->getDateTime())
|
|
: null,
|
|
);
|
|
}
|
|
}
|