store/app/Models/Category.php

33 lines
916 B
PHP

<?php
namespace App\Models;
use App\Models\Concerns\InteractsWithActivityLog;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Sluggable\Attributes\Sluggable;
#[Guarded(['id'])]
#[Sluggable(from: 'name', to: 'slug')]
class Category extends Model
{
// 1. Use Trait
use HasFactory, InteractsWithActivityLog, SoftDeletes;
// 2. Other Methods
public static function getActiveWithProducts(): Collection
{
return self::whereHas('products')->get(['id', 'name', 'slug']);
}
// 3. Relation
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class, 'product_categories');
}
}