115 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
class Product extends Model
{
protected $fillable = [
'nom',
'reference',
'categorie',
'fabricant',
'stock_actuel',
'stock_minimum',
'unite',
'prix_unitaire',
'date_expiration',
'numero_lot',
'conditionnement_nom',
'conditionnement_quantite',
'conditionnement_unite',
'image',
'fiche_technique_url',
'fournisseur_id',
];
protected $casts = [
'stock_actuel' => 'decimal:2',
'stock_minimum' => 'decimal:2',
'prix_unitaire' => 'decimal:2',
'conditionnement_quantite' => 'decimal:2',
'date_expiration' => 'date',
];
/**
* Get the fournisseur that owns the product.
*/
public function fournisseur(): BelongsTo
{
return $this->belongsTo(Fournisseur::class);
}
/**
* Get the category that owns the product.
*/
public function category(): BelongsTo
{
return $this->belongsTo(ProductCategory::class, 'categorie', 'name');
}
/**
* Handle image upload
*/
public function uploadImage($image)
{
if ($image) {
// Delete old image if exists
if ($this->image) {
$this->deleteImage();
}
// Store the new image
$imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
$imagePath = $image->storeAs('products', $imageName, 'public');
$this->image = $imagePath;
$this->save();
return $imagePath;
}
return null;
}
/**
* Delete the product image
*/
public function deleteImage()
{
if ($this->image) {
Storage::disk('public')->delete($this->image);
$this->image = null;
$this->save();
}
}
/**
* Get the full URL of the image
*/
public function getImageUrlAttribute()
{
if ($this->image) {
return Storage::url($this->image);
}
return null;
}
/**
* Boot the model
*/
protected static function boot()
{
parent::boot();
static::deleting(function ($product) {
// Delete the image when the product is deleted
$product->deleteImage();
});
}
}