ldc-legaulois/app/Models/Actu.php
2022-02-10 16:14:58 +01:00

92 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class Actu extends Model
{
use HasFactory;
protected $fillable = [
'title',
'slug',
'seo_title',
'seo_description',
'header',
'content',
'picture_alt',
'status'
];
protected $attributes = [
'front' => false
];
protected static function booted()
{
static::creating(function (Actu $actu) {
$actu->slug = Str::slug($actu->title);
$actu->header = clean($actu->header);
$actu->content = clean($actu->content);
// actu non mise en avvant si pas publié
if (!$actu->status) {
$actu->front = false;
}
});
static::updating(function (Actu $actu) {
$actu->slug = Str::slug($actu->title);
$actu->header = clean($actu->header);
$actu->content = clean($actu->content);
// actu non mise en avvant si pas publié
if (!$actu->status) {
$actu->front = false;
}
});
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
static::created(function (Actu $actu) {
Cache::delete('ActusGlobal');
});
static::updated(function (Actu $actu) {
Cache::delete('ActusGlobal');
Cache::delete("ActuRendered_$actu->id");
});
static::deleted(function (Actu $actu) {
Cache::delete('ActusGlobal');
Cache::delete("ActuRendered_$actu->id");
});
}
public function getRouteKeyName()
{
return 'slug';
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function notifiable()
{
return $this->morphOne(Notifications::class, 'notifiable');
}
public static function getCachedActus()
{
if (!Cache::has('ActusGlobal')) {
self::setCachedActus();
}
return Cache::get('ActusGlobal');
}
protected static function setCachedActus()
{
$actus = Actu::with('tags')->whereStatus(true)->whereFront(true)
->orderBy('updated_at', 'DESC')->limit(3)->get();
Cache::put('ActusGlobal', $actus);
}
}