Skip to content

Commit e8f7864

Browse files
committed
Add random unique hash code trait for models
1 parent 24f9b4b commit e8f7864

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/Traits/HasHash.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace Codebarista\LaravelEssentials\Traits;
4+
5+
use Codebarista\LaravelEssentials\Facades\DB;
6+
use Illuminate\Database\Eloquent\Model;
7+
use Illuminate\Support\Facades\Schema;
8+
use Illuminate\Support\Str;
9+
10+
trait HasHash
11+
{
12+
protected static function bootHasHash(): void
13+
{
14+
// create and set a unique hash code for model
15+
static::creating(static function (Model $model) {
16+
$table = $model->getTable();
17+
if (Schema::hasColumn($table, 'hash')) {
18+
$column = Schema::getColumnType($table, 'hash', true);
19+
$length = preg_replace('/\D/', '', $column);
20+
$model->setAttribute('hash', self::getUniqueHash($table, $length));
21+
}
22+
});
23+
}
24+
25+
protected static function getUniqueHash(string $table, int $length, int $iterations = 0): ?string
26+
{
27+
$hash = Str::random($length);
28+
29+
// we've tried enough at this point
30+
if ($iterations > 9) {
31+
return $hash;
32+
}
33+
34+
if (DB::table($table)->where('hash', $hash)->exists()) {
35+
return self::getUniqueHash($table, $length, $iterations + 1);
36+
}
37+
38+
return $hash;
39+
}
40+
}

0 commit comments

Comments
 (0)