ldc-doux/app/Models/Post.php
Sebastien Hattry d3b9865717 delete picture when a field is deleted
+ fix css bugs
2022-01-07 17:29:55 +01:00

76 lines
2.1 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Utils;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
class Post extends Model
{
use HasFactory;
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'date_start' => 'datetime',
'date_end' => 'datetime',
];
protected $fillable = [
'title',
'text',
'picture_home',
'alt_text_picture_home',
'picture_news',
'alt_text_picture_news',
'date_start',
'date_end',
'on_top'
];
protected static function boot()
{
static::creating(function (Post $post) {
if ($post->picture_home) {
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
if ($post->picture_news) {
$post->picture_news = Utils::storeImage($post->picture_news, $post->getTable());
}
});
static::updating(function (Post $post) {
if ($post->picture_home) {
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
if ($post->picture_news) {
$post->picture_news = Utils::storeImage($post->picture_news, $post->getTable());
}
});
static::deleted(function (Post $post) {
if ($post->picture_home) {
$urlPicture = public_path() . $post->picture_home;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
if ($post->picture_news) {
$urlPicture = public_path() . $post->picture_news;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
});
parent::boot();
}
}