ldc-doux/app/Models/Product.php

108 lines
2.6 KiB
PHP
Raw Normal View History

2021-12-22 17:32:05 +01:00
<?php
namespace App\Models;
use App\Lib\Utils;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use Spatie\Translatable\HasTranslations;
2021-12-22 17:32:05 +01:00
class Product extends Model
{
use HasFactory;
use HasTranslations;
2021-12-22 17:32:05 +01:00
2022-08-29 17:23:10 +02:00
/**
* The attributes that are mass assignable.
*
* @var array
*/
2021-12-22 17:32:05 +01:00
protected $fillable = [
'gamme_id',
'name',
'slug',
'description',
'picture',
'alt_text_picture',
2021-12-24 15:58:59 +01:00
'pictos',
'plusproduit',
2021-12-22 17:32:05 +01:00
'is_published',
'is_on_top',
'is_news',
2021-12-22 17:32:05 +01:00
'is_halal',
'is_food_service',
'seo_title',
'seo_description',
];
2022-08-29 17:23:10 +02:00
/**
* The attributes that are translatable.
*
* @var array
*/
public $translatable = [
'name',
'slug',
'description',
2022-01-23 14:52:07 +01:00
'picture',
'alt_text_picture',
'pictos',
'plusproduit',
'seo_title',
2021-12-22 17:32:05 +01:00
'seo_description',
];
2022-08-29 17:23:10 +02:00
/**
* Perform any actions required after the model boots.
*
* @return void
*/
2021-12-22 17:32:05 +01:00
protected static function boot()
{
static::creating(function (Product $product) {
if (is_a($product->picture, "SplFileInfo")) {
2021-12-22 17:32:05 +01:00
$product->picture = Utils::storeImage($product->picture, $product->getTable());
}
});
static::updating(function (Product $product) {
if (is_a($product->picture, "SplFileInfo")) {
2021-12-22 17:32:05 +01:00
$product->picture = Utils::storeImage($product->picture, $product->getTable());
}
});
static::deleted(function (Product $product) {
if ($product->picture) {
$urlPicture = public_path() . $product->picture;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
2022-08-29 17:23:10 +02:00
// Delete des images de plus produit.
$plusproduit = json_decode($product->plusproduit);
foreach ($plusproduit as $plus) {
$urlPicture = public_path() . $plus->url;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
});
2021-12-22 17:32:05 +01:00
parent::boot();
}
2021-12-24 15:58:59 +01:00
/**
* Get the Range that owns the product.
2022-08-29 17:23:10 +02:00
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
2021-12-24 15:58:59 +01:00
*/
public function gamme()
{
return $this->belongsTo(Gamme::class);
}
2021-12-22 17:32:05 +01:00
}