File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments