Skip to content

Commit bdab08c

Browse files
Implement Custom Properties in Media
1 parent ebecec2 commit bdab08c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/Eloquent/Media.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,18 @@
88
use Illuminate\Database\Eloquent\Factories\HasFactory;
99
use Illuminate\Database\Eloquent\Model;
1010
use Illuminate\Database\Eloquent\Relations\MorphTo;
11+
use Illuminate\Support\Facades\Schema;
1112

1213
class Media extends Model
1314
{
1415
use HasFactory;
1516

1617
protected $guarded = [];
1718
protected $table = 'medias';
19+
protected $casts = [
20+
'custom_properties' => 'array',
21+
'size' => 'integer',
22+
];
1823

1924
protected static function newFactory()
2025
{
@@ -37,4 +42,45 @@ public function download(): ?string
3742
{
3843
return \Storage::disk($this->disk)->url($this->file_name);
3944
}
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+
}
4086
}

0 commit comments

Comments
 (0)