|
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 | {
|
@@ -56,4 +61,45 @@ public function humanReadableSize($precision = 2): ?string
|
56 | 61 | return $this->size;
|
57 | 62 | }
|
58 | 63 | }
|
| 64 | + |
| 65 | + /** |
| 66 | + * @param string $key |
| 67 | + * @return mixed|null |
| 68 | + */ |
| 69 | + public function getAttribute($key) |
| 70 | + { |
| 71 | + if (! $this->isRealAttribute($key)) { |
| 72 | + return $this->getAttribute('custom_properties')[$key] ?? null; |
| 73 | + } |
| 74 | + |
| 75 | + return parent::getAttribute($key); |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * @param string $key |
| 80 | + * @param mixed $value |
| 81 | + * @return Model |
| 82 | + */ |
| 83 | + public function setAttribute($key, $value) |
| 84 | + { |
| 85 | + if (! $this->isRealAttribute($key)) { |
| 86 | + return $this->updateCustomProperty($key, $value); |
| 87 | + } |
| 88 | + |
| 89 | + return parent::setAttribute($key, $value); |
| 90 | + } |
| 91 | + |
| 92 | + protected function updateCustomProperty(string $key, $value): self |
| 93 | + { |
| 94 | + $properties = $this->getAttribute('custom_properties'); |
| 95 | + $properties[$key] = $value; |
| 96 | + $this->setAttribute('custom_properties', $properties); |
| 97 | + |
| 98 | + return $this; |
| 99 | + } |
| 100 | + |
| 101 | + protected function isRealAttribute(string $name): bool |
| 102 | + { |
| 103 | + return Schema::hasColumn($this->getTable(), $name) ?? false; |
| 104 | + } |
59 | 105 | }
|
0 commit comments