Initial commit - WASL Digital Wallet
This commit is contained in:
40
Backend/app/Models/Traits/HasUuid.php
Normal file
40
Backend/app/Models/Traits/HasUuid.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Traits;
|
||||
|
||||
/**
|
||||
* Auto-generates a UUID on creation and provides uuid-based route binding.
|
||||
* Every WASL model exposed to the API MUST use this trait.
|
||||
*/
|
||||
trait HasUuid
|
||||
{
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function ($model) {
|
||||
if (empty($model->getAttribute('uuid'))) {
|
||||
$model->setAttribute('uuid', str()->uuid()->toString());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'uuid';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve by UUID instead of BIGINT primary key.
|
||||
*/
|
||||
public function resolveRouteBinding($value, $field = null)
|
||||
{
|
||||
return $this->where('uuid', $value)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: filter by UUID.
|
||||
*/
|
||||
public function scopeWhereUuid($query, string $uuid)
|
||||
{
|
||||
return $query->where('uuid', $uuid);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user