ldc-wenn-dann-mit-respekt/app/Models/StoreRegion.php
Alexis Gousseau 9d6c7fdb60 add models
2023-03-15 15:57:35 +01:00

100 lines
2.3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Model;
/**
* @property integer $id
* @property integer $group_id
* @property string $name
* @property string $picture
* @property string $created_at
* @property string $updated_at
* @property Store[] $stores
* @property StoreGroup $storeGroup
*/
class StoreRegion extends Model
{
/**
* @var array
*/
protected $fillable = [
'group_id',
'name',
'picture',
'created_at',
'updated_at'
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
});
}
// * METHODS
/**
* Undocumented function
*
* @param Model $model
* @return void
*/
private static function manageFields(Model $model)
{
self::assertFieldIsUnique('name', $model->name);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
/**
* Asserts using validation that the field is unique.
*
* @param string $nameField
* @param mixed $valueField
* @param integer|null $id
* @return void
*/
private static function assertFieldIsUnique(string $nameField, string $valueField, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id);
}
// * RELATIONSHIPS
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function stores()
{
return $this->hasMany('App\Models\Store', 'region_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function storeGroup()
{
return $this->belongsTo('App\Models\StoreGroup', 'group_id');
}
}