ldc-gen-game-web/app/Models/Product.php
2025-08-14 14:12:13 +00:00

120 lines
3.3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\ActivityLog;
use App\Traits\Models\IsCachedAsCollection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Product.
*
* @property string $name Name
* @property string $picture Path of the picture
* @property string $picture_alt Alt text for the picture
* @property string $picture_title Title text for the picture
* @property string $ean_code Ean code
* @property-read \Illuminate\Support\Carbon $created_at Creation Date.
* @property-read \Illuminate\Support\Carbon $updated_at Last update Date.
*
* @property-read \App\Models\Range[] $range Associated range.
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Participation[] $participations
* Associated participations.
*
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/
class Product extends Model
{
use ActivityLog;
use HasFactory;
use IsCachedAsCollection;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'picture',
'picture_alt',
'picture_title',
'ean_code',
'range_id',
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::created(fn () => self::removeCached());
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
self::removeCached();
FileStorageHelper::removeOldFile($model, 'picture');
});
static::deleted(function (self $model) {
self::removeCached();
FileStorageHelper::removeFile($model, 'picture');
});
}
// * METHODS
/**
* Common methods function.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model)
{
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
// * RELATIONSHIPS
/**
* Range relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function range(): BelongsTo
{
return $this->belongsTo(Range::class);
}
/**
* Participations relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function participations(): HasMany
{
return $this->hasMany(Participation::class);
}
/**
* Activities logs One-to-many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function activityLogs(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(ActivityLog::class);
}
}