ldc-legaulois/app/Models/Profession.php

102 lines
3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
/**
* @property string $title Profession title.
* @property string $picture Profession picture.
* @property string $picture_alt Picture alt attribute.
* @property string $picture_title Picture title attribute.
* @property string $jobs_list Profession jobs.
* @property string $job_url Digital recruiters url.
* @property boolean $published Profession publish status.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*/
class Profession extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'title',
'picture',
'picture_alt',
'picture_title',
'jobs_list',
'job_url',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'jobs_list' => 'array',
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $profession) {
$profession->picture = FileStorageHelper::storeFile($profession, $profession->picture, true);
});
static::created(function () {
self::resetCache();
});
static::updating(function (self $profession) {
$profession->picture = FileStorageHelper::storeFile($profession, $profession->picture, true);
});
static::updated(function (self $profession) {
FileStorageHelper::removeOldFile($profession, 'picture');
self::resetCache();
});
static::deleted(function (self $profession) {
FileStorageHelper::removeFile($profession, 'picture');
self::resetCache();
});
}
// * METHODS
/**
* Reset all cache elements related to this model.
*
* @return void
*/
private static function resetCache()
{
Cache::forget('5publishedProfessions');
self::get5Published();
}
/**
* Get 5 published professions.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function get5Published(): \Illuminate\Database\Eloquent\Collection
{
return Cache::rememberForever('5publishedProfessions', function () {
return self::query()->where('published', true)->take(5)->get();
});
}
}