12
12
use Illuminate \Database \Eloquent \Relations \HasOne ;
13
13
use Illuminate \Database \Eloquent \SoftDeletes ;
14
14
use Illuminate \Support \Facades \Gate ;
15
+ use Illuminate \Support \Str ;
15
16
16
17
class Service extends Model
17
18
{
@@ -25,8 +26,24 @@ class Service extends Model
25
26
'team_id ' ,
26
27
];
27
28
29
+ // Add this line to make slug the routing key
30
+ public function getRouteKeyName ()
31
+ {
32
+ return 'slug ' ;
33
+ }
34
+
28
35
protected static function booted ()
29
36
{
37
+ static ::creating (function (Service $ service ) {
38
+ $ service ->slug = $ service ->generateUniqueSlug ($ service ->name );
39
+ });
40
+
41
+ static ::updating (function (Service $ service ) {
42
+ if ($ service ->isDirty ('name ' )) {
43
+ $ service ->slug = $ service ->generateUniqueSlug ($ service ->name );
44
+ }
45
+ });
46
+
30
47
self ::saved (function (Service $ service ) {
31
48
if (! $ service ->docker_name ) {
32
49
$ service ->docker_name = $ service ->makeResourceName ($ service ->name );
@@ -57,6 +74,27 @@ protected static function booted()
57
74
});
58
75
}
59
76
77
+ protected function generateUniqueSlug ($ name )
78
+ {
79
+ $ slug = Str::slug ($ name );
80
+ $ originalSlug = $ slug ;
81
+ $ vocabulary = ['cat ' , 'dog ' , 'bird ' , 'fish ' , 'mouse ' , 'rabbit ' , 'turtle ' , 'frog ' , 'bear ' , 'lion ' ];
82
+ $ adjectives = ['happy ' , 'brave ' , 'bright ' , 'cheerful ' , 'confident ' , 'creative ' , 'determined ' , 'energetic ' , 'friendly ' , 'funny ' , 'generous ' , 'kind ' ];
83
+ shuffle ($ vocabulary );
84
+ shuffle ($ adjectives );
85
+
86
+ foreach ($ adjectives as $ adjective ) {
87
+ foreach ($ vocabulary as $ word ) {
88
+ $ uniqueSlug = $ originalSlug .'- ' .$ adjective .'- ' .$ word ;
89
+ if (! self ::where ('slug ' , $ uniqueSlug )->where ('id ' , '!= ' , $ this ->id )->exists ()) {
90
+ return $ uniqueSlug ;
91
+ }
92
+ }
93
+ }
94
+
95
+ return $ slug .'- ' .$ adjectives [0 ].'- ' .$ vocabulary [0 ].'- ' .time ();
96
+ }
97
+
60
98
public function swarm (): BelongsTo
61
99
{
62
100
return $ this ->belongsTo (Swarm::class);
0 commit comments