8
8
use Illuminate \Database \Eloquent \Factories \HasFactory ;
9
9
use Illuminate \Database \Eloquent \Model ;
10
10
use Illuminate \Database \Eloquent \Relations \MorphTo ;
11
+ use Illuminate \Support \Facades \Schema ;
11
12
12
13
class Media extends Model
13
14
{
14
15
use HasFactory;
15
16
16
17
protected $ guarded = [];
17
18
protected $ table = 'medias ' ;
19
+ protected $ casts = [
20
+ 'custom_properties ' => 'array ' ,
21
+ 'size ' => 'integer ' ,
22
+ ];
18
23
19
24
protected static function newFactory ()
20
25
{
@@ -37,4 +42,45 @@ public function download(): ?string
37
42
{
38
43
return \Storage::disk ($ this ->disk )->url ($ this ->file_name );
39
44
}
45
+
46
+ /**
47
+ * @param string $key
48
+ * @return mixed|null
49
+ */
50
+ public function getAttribute ($ key )
51
+ {
52
+ if (! $ this ->isRealAttribute ($ key )) {
53
+ return $ this ->getAttribute ('custom_properties ' )[$ key ] ?? null ;
54
+ }
55
+
56
+ return parent ::getAttribute ($ key );
57
+ }
58
+
59
+ /**
60
+ * @param string $key
61
+ * @param mixed $value
62
+ * @return Model
63
+ */
64
+ public function setAttribute ($ key , $ value )
65
+ {
66
+ if (! $ this ->isRealAttribute ($ key )) {
67
+ return $ this ->updateCustomProperty ($ key , $ value );
68
+ }
69
+
70
+ return parent ::setAttribute ($ key , $ value );
71
+ }
72
+
73
+ protected function updateCustomProperty (string $ key , $ value ): self
74
+ {
75
+ $ properties = $ this ->getAttribute ('custom_properties ' );
76
+ $ properties [$ key ] = $ value ;
77
+ $ this ->setAttribute ('custom_properties ' , $ properties );
78
+
79
+ return $ this ;
80
+ }
81
+
82
+ protected function isRealAttribute (string $ name ): bool
83
+ {
84
+ return Schema::hasColumn ($ this ->getTable (), $ name ) ?? false ;
85
+ }
40
86
}
0 commit comments