22
33namespace LaraZeus \Bolt \Models ;
44
5+ use Illuminate \Database \Eloquent \Casts \Attribute ;
56use Illuminate \Database \Eloquent \Factories \Factory ;
67use Illuminate \Database \Eloquent \Factories \HasFactory ;
78use Illuminate \Database \Eloquent \Model ;
@@ -24,11 +25,11 @@ class Collection extends Model
2425
2526 protected $ guarded = [];
2627
27- public $ translatable = ['name ' , 'values ' ];
28+ public array $ translatable = ['name ' , 'values ' ];
2829
2930 public function getTable (): string
3031 {
31- return config ('zeus-bolt.table-prefix ' ) . 'collections ' ;
32+ return config ('zeus-bolt.table-prefix ' ). 'collections ' ;
3233 }
3334
3435 public function getValuesListAttribute (): ?string
@@ -47,22 +48,38 @@ public function getValuesListAttribute(): ?string
4748 return null ;
4849 }
4950
51+ protected function name (): Attribute
52+ {
53+ return Attribute::make (
54+ get: fn ($ value ) => (filled ($ value ))
55+ ? $ value
56+ : $ this ->getRawOriginal ('name ' ),
57+ );
58+ }
59+
5060 /**
51- * Returns the values as a collection. Translatable variables are always cast as an array. This function transforms
52- * it to a collection.
53- * Note: The newer Attribute approach does not seem to be compatible with laravel-translatable ;-(.
54- * @param $value
55- * @return \Illuminate\Support\Collection
61+ * Returns the values as a collection. Translatable variables are always cast as an array.
62+ * This function transforms it to a collection.
63+ *
64+ * @return Attribute
65+ * @throws \JsonException
5666 */
57- public function getValuesAttribute ( $ value )
67+ protected function values (): Attribute
5868 {
59- if (is_array ($ value )){
60- return collect ($ value );
61- }
62- if (is_string ($ value )){
63- return collect (json_encode ($ value ));
64- }
65- return $ value ;
69+ return Attribute::make (
70+ get: function ($ value ) {
71+ $ value = (filled ($ value )) ? $ value : $ this ->getRawOriginal ('values ' );
72+
73+ if (is_string ($ value )) {
74+ $ value = collect (json_decode ($ value , JSON_THROW_ON_ERROR , 512 , JSON_THROW_ON_ERROR ));
75+ }
76+
77+ if (is_array ($ value )) {
78+ $ value = collect ($ value );
79+ }
80+ return $ value ;
81+ },
82+ );
6683 }
6784
6885 protected static function newFactory (): Factory
0 commit comments