File "Product.php"

Full Path: /home/tecassol/public_html/tecas-solar.ma/app/Models/Product.php
File size: 2.48 KB
MIME-type: text/x-php
Charset: utf-8

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use LaravelArchivable\Archivable;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Product extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia, Archivable;

    protected $fillable = [
        "brand_id",
        "name",
        "slug",
        "old_slug",
        "description",
        "content",
        "price",
        "sale_price",
        "current_stock",
        "is_published",
        "published_at",
        "images",
        "sku",
        "security_stock",
        "barcode",
        "seo_title",
        "seo_description",
        "og_image",
        "archived_at",
        "order",
    ];

    protected $casts = [
        'is_published' => 'boolean',
        'published_at' => 'datetime',
        'images' => 'array',
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'current_stock' => 'integer',
        'security_stock' => 'integer',
    ];

    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class, 'product_category');
    }

    public function brand(): BelongsTo
    {
        return $this->belongsTo(Brand::class);
    }

    public function orders(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(Review::class);
    }
    public function coupons(): MorphToMany
    {
        return $this->morphToMany(Coupon::class, 'discountable', 'coupon_details');
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('products');
        $this->addMediaCollection('technical-sheet')
            ->singleFile();
    }

    public function archive()
    {
        $this->update(['archived_at' => now()]);
    }

    public function unarchive()
    {
        $this->update(['archived_at' => null]);
    }

    public function scopePublished($query, bool $condition = true)
    {
        return $query->where('is_published', $condition);
    }

    public function scopeFirstCategory($query)
    {
        return $this->categories()->first();
    }
}