main

filamentphp/demo

Last updated at: 29/12/2023 09:43

Product.php

TLDR

This file defines the Product model for the Shop section of the application. It extends the Model class and implements the HasMedia interface for handling media files. The model has relationships with the Brand, Category, and Comment models.

Classes

Product

The Product class represents a product in the Shop section of the application. It extends the Model class and implements the HasMedia interface. The class contains the following methods and properties:

  • $table: Specifies the table to use for storing product records.
  • $casts: Defines the data types of certain attributes, including featured, is_visible, backorder, requires_shipping, and published_at.
  • brand(): Returns the relationship between a product and its brand. It belongs to the Brand model.
  • categories(): Returns the relationship between a product and its categories. It belongs to many Category models through the shop_category_product pivot table.
  • comments(): Returns the relationship between a product and its comments. It has many Comment models through polymorphism.
<?php

namespace App\Models\Shop;

use App\Models\Comment;
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\MorphMany;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

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

    /**
     * @var string
     */
    protected $table = 'shop_products';

    /**
     * @var array<string, string>
     */
    protected $casts = [
        'featured' => 'boolean',
        'is_visible' => 'boolean',
        'backorder' => 'boolean',
        'requires_shipping' => 'boolean',
        'published_at' => 'date',
    ];

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

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

    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}