ldc-loue/app/Models/Recipe.php
Alexis Gousseau 4a78ce9369 sprint 4
2022-11-07 16:24:39 +01:00

93 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Recipe extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'slug',
'seo_title',
'seo_description',
'banner',
'banner_alt',
'banner_title',
'category',
'servings',
'preparation',
'cooking',
'ingredients',
'description',
'video',
'picture',
'picture_alt',
'picture_title',
'status'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'ingredients' => 'array'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
static::assertTitleIsUnique($model->title);
$model->slug = Str::slug($model->title);
$model->banner = FileStorageHelper::storeFile($model, $model->banner);
$model->picture = FileStorageHelper::storeFile($model, $model->picture);
});
static::updating(function (self $model) {
static::assertTitleIsUnique($model->title, $model->id);
$model->slug = Str::slug($model->title);
// * Store new banner if changed
if ($model->banner != $model->getOriginal('banner')) {
$model->banner = FileStorageHelper::storeFile($model, $model->banner);
}
// * Store new picture if changed
if ($model->picture != $model->getOriginal('picture')) {
$model->picture = FileStorageHelper::storeFile($model, $model->picture);
}
});
}
// * METHODS
/**
* Asserts using validation that the title is unique
*
* @param mixed $title
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If an actu title already exists.
*/
private static function assertTitleIsUnique($title, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
}
}