ldc-loue/app/Models/Recipe.php
Alexis Gousseau 2211428f9a retour review
2022-12-15 14:06:36 +01:00

95 lines
2.2 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) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
}
// * METHODS
/**
* Undocumented function
*
* @param Model $model
* @return void
*/
private static function manageFields(Model $model)
{
static::assertTitleIsUnique($model->title, $model->id);
$model->banner = FileStorageHelper::storeFile($model, $model->banner);
$model->picture = FileStorageHelper::storeFile($model, $model->picture);
$model->slug = Str::slug($model->title);
}
/**
* 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);
}
}